<?php

App::import('Sanitize');

class ProductsController extends AppController {

    var $name = 'Products';
    var $uses = array('Product', 'Note', 'User', 'Category', 'Categorybrand', 'Brand', 'Imagetitle', 'ProductImage', 'Field', 'ProductAdditionalFieldValue', 'Sizetitle', 'Sizevalue', 'ProductSize', 'Shipping', 'HandleTime', 'ProductShipping', 'Country', 'ProductInternationalShipping', 'Sizelabel');
    var $components = array('Uploader.Uploader', 'Email');
    var $helpers = array('Thumbnail', 'Csv', 'Fck');

    function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allowedActions = array('chkduplicatefield', 'autobrand', 'brandnamebyid', 'viewdispute', 'breadcrumchkHasParent', 'color_menu', 'size_menu', 'gallery_popup', 'deletethumbimage', 'fetchadditionalfields_details', 'fetch_labels_fields_details', 'store', 'report_problem', 'details', 'advance_search', 'search_result', 'browsebycategory', 'feedback_chk_byuser', 'getnamebyid', 'brand_menu', 'browsebybrand', 'browsebycompletedlist', 'browsebyprice', 'browsebysize', 'browsebycolor', 'fetchsizes_edit', 'fetchadditionalfields_details_label');
        //fill with associated array of name, type, size to the corresponding column name
        $this->Uploader->uploadDir = 'img/uploads/';
        $this->Uploader->enableUpload = true;
        $this->Uploader->maxFileSize = '1M'; // 1 Megabytes
        $this->Uploader->maxNameLength = 50;
        $this->Uploader->tempDir = TMP;
        $this->Uploader->mime('image', 'gif', 'image/gif');
    }

    function index() {
        $this->Product->Behaviors->attach('Containable');
        if (!empty($this->data['keywords']) AND $this->data['search_by'] == 'item_title') {
            $this->paginate = array('limit' => 25, 'contain' => array('Note'), 'conditions' => array('Product.products_title LIKE' => '%' . $this->data['keywords'] . '%', 'Product.user_id' => $this->Auth->User('id'),
                    'OR' => array(array('Product.products_status' => 'Active'), array('Product.products_status' => 'Approved'))), 'order' => array('Product.id' => 'desc'));
        } elseif (!empty($this->data['keywords']) AND $this->data['search_by'] == 'item_number') {

            $this->paginate = array('limit' => 25, 'contain' => array('Note'), 'conditions' => array('Product.id' => $this->data['keywords'], 'Product.user_id' => $this->Auth->User('id'),
                    'OR' => array(array('Product.products_status' => 'Active'), array('Product.products_status' => 'Approved'))), 'order' => array('Product.id' => 'desc'));
        } else {
            $this->paginate = array('limit' => 25, 'contain' => array('Note'),
                'conditions' => array('Product.user_id' => $this->Auth->User('id'),
                    'OR' => array(array('Product.products_status' => 'Active'), array('Product.products_status' => 'Approved'))), 'order' => array('Product.id' => 'desc'));
        }
        //left nav           
        $this->set('item', $this->Category->categoryArray());
        $this->set('products', $this->paginate());
        $this->layout = "innerhome";
    }

    function featured($id=null, $id2=null) {
        $this->layout = false;
        $this->autoRender = false;
        if ($this->Product->isowner($id2, $this->Auth->User('id'), $this->Auth->User('group_id'))) {
            $this->data['Product']['id'] = $id2;
            if ($id == 1) {
                $this->data['Product']['featured'] = "Pending";
                $this->Session->setFlash(__('The Product has been featured successfully.', true));
            }
            if ($id == 0) {
                $this->data['Product']['featured'] = "No";
                $this->Session->setFlash(__('The Product has been successfully removed from feature.', true));
            }
            if ($id == 2) {
                $this->data['Product']['featured'] = "Yes";
                $this->Session->setFlash(__('The Product has been featured successfully.', true));
            }
            $this->Product->save($this->data);
        } else {
            $this->Session->setFlash(__('Sorry! you are not the actual seller of this product to change the feature.', true));
        }
        //$this->redirect(array('action' => 'index'));
        $this->redirect($this->referer());
    }

    function makefeatured() {
        $this->layout = false;
        $this->autoRender = false;
        $no = 0;
        foreach ($_POST['pid'] as $pid) {
            if ($this->Product->isowner($pid, $this->Auth->User('id'), $this->Auth->User('group_id'))) {
                $this->data['Product']['id'] = $pid;
                $this->data['Product']['featured'] = "Pending";
                $this->Session->setFlash(__('Products has been featured successfully.', true));
                $this->Product->save($this->data);
            }
        }
        //$this->redirect(array('action' => 'index'));
    }

    function remove_featured() {
        $this->layout = false;
        $this->autoRender = false;
        $no = 0;
        foreach ($_POST['pid'] as $pid) {
            if ($this->Product->isowner($pid, $this->Auth->User('id'), $this->Auth->User('group_id'))) {
                $this->data['Product']['id'] = $pid;
                $this->data['Product']['featured'] = "No";
                $this->Session->setFlash(__('Products has been successfully removed from feature.', true));
                $this->Product->save($this->data);
            }
        }
        //$this->redirect(array('action' => 'index'));
    }

    function removefeatured($id=null) {
        $this->layout = false;
        $this->autoRender = false;
        if ($this->Product->isowner($id, $this->Auth->User('id'), $this->Auth->User('group_id'))) {
            $this->data['Product']['id'] = $id;
            $this->data['Product']['featured'] = "No";
            $this->Product->save($this->data);
            $this->Session->setFlash(__('The Product has been successfully removed from feature.', true));
        } else {
            $this->Session->setFlash(__('Sorry! you are not the actual seller of this product to change the feature.', true));
        }
    }

    function add() {
        $this->layout = "innerhome";

        if (!empty($this->data)) {
            //$this->data = Sanitize::clean($this->data, array('remove_html' => true));
            $this->Product->set($this->data);
            if ($this->Product->validates()) {
                //uploading products image then add products
                if ($data = $this->Uploader->uploadAll()) {
                    // Upload successful
                    $this->data['Product']['products_thumbnailImage'] = $data['fileName']['name'];

                    if (empty($this->data['Product']['global_brands'])) {
                        $this->data['Product']['global_brands'] = 0;
                    }
                    //if user suggested new brand
                    if (isset($this->data['Product']['sugestbrands']) AND empty($this->data['Product']['global_brands'])) {
                        $this->data['Brand']['brand_type'] = "brand";
                        $this->data['Brand']['brand_description'] = $this->data['Product']['sugestbrands'];
                        $this->Brand->create();
                        $this->Brand->save($this->data['Brand']);
                        $brand_id = $this->Brand->getlastinsertid();
                        $this->data['Categorybrand']['brand_type'] = "brand";
                        $this->data['Categorybrand']['brand_id'] = $brand_id;
                        $this->data['Categorybrand']['category_id'] = $this->data['Product']['category_id'];
                        $this->Categorybrand->create();
                        $this->Categorybrand->save($this->data['Categorybrand']);
                        $this->data['Product']['global_brands'] = $brand_id;
                    }

                    if (empty($this->data['Product']['global_styles'])) {
                        $this->data['Product']['global_styles'] = 0;
                    }
                    //if user suggested new style
                    if (isset($this->data['Product']['sugeststyles']) AND empty($this->data['Product']['global_styles'])) {
                        $this->data['Brand']['brand_type'] = "style";
                        $this->data['Brand']['brand_description'] = $this->data['Product']['sugeststyles'];
                        $this->Brand->create();
                        $this->Brand->save($this->data['Brand']);
                        $style_id = $this->Brand->getlastinsertid();

                        $this->data['Categorybrand']['brand_type'] = "style";
                        $this->data['Categorybrand']['brand_id'] = $style_id;
                        $this->data['Categorybrand']['category_id'] = $this->data['Product']['category_id'];
                        $this->Categorybrand->create();
                        $this->Categorybrand->save($this->data['Categorybrand']);
                        $this->data['Product']['global_styles'] = $style_id;
                    }
                    if (empty($this->data['Product']['global_conditions'])) {
                        $this->data['Product']['global_conditions'] = 0;
                    }
                    //if user suggested new condition
                    if (isset($this->data['Product']['sugestconditions']) AND empty($this->data['Product']['global_conditions'])) {
                        $this->data['Brand']['brand_type'] = "condition";
                        $this->data['Brand']['brand_description'] = $this->data['Product']['sugestconditions'];
                        $this->Brand->create();
                        $this->Brand->save($this->data['Brand']);
                        $condition_id = $this->Brand->getlastinsertid();

                        $this->data['Categorybrand']['brand_type'] = "condition";
                        $this->data['Categorybrand']['brand_id'] = $condition_id;
                        $this->data['Categorybrand']['category_id'] = $this->data['Product']['category_id'];
                        $this->Categorybrand->create();
                        $this->Categorybrand->save($this->data['Categorybrand']);
                        $this->data['Product']['global_conditions'] = $condition_id;
                    }
                    $this->data['Product']['products_createDate'] = date("Y-m-d H:s:i");
                    $nextWeek = strtotime("+1 week");
                    $this->data['Product']['products_expiredDate'] = date("Y-m-d H:s:i", $nextWeek);

                    if ($this->Session->Check('Auth.User.group_id') == 3) {
                        $this->data['Product']['products_status'] = "Approved";
                    } else {
                        $this->data['Product']['products_status'] = "Pending";
                    }

                    $this->Product->create();
                    if ($this->Product->save($this->data)) {
                        $product_id = $this->Product->getlastinsertid();
                        unset($data['fileName']);
                        if (isset($data)) {
                            $i = 1;
                            foreach ($data as $key => $val) {
                                if (isset($val)) {
                                    $this->data['ProductImage'][$i]['image'] = $val['name'];
                                    $this->data['ProductImage'][$i]['product_id'] = $product_id;
                                    $this->data['ProductImage'][$i]['category_id'] = $this->data['cat_id'];
                                    $i++;
                                }
                            }
                            if (isset($this->data['ProductImage'])) {
                                $this->ProductImage->create();
                                $this->ProductImage->saveAll($this->data['ProductImage']);
                            }
                        }
                        //Additional Fields
                        if (isset($this->data['AdditionalFieldValue'])) {
                            $i = 0;
                            foreach ($this->data['AdditionalFieldValue'] as $tmp) {
                                if (isset($tmp['values'])) {
                                    $this->data['ProductAdditionalFieldValue'][$i]['field_id'] = $tmp['field_id'];
                                    $this->data['ProductAdditionalFieldValue'][$i]['values'] = $tmp['values'];
                                    /* if(isset($tmp['values'])){
                                      $options['fields']=array("Field.field_value");
                                      $options['conditions']=array("Field.id"=>$tmp['field_id']);
                                      $fields=$this->Field->find('first',$options);
                                      $dropdown_values=explode(",",$fields['Field']['field_value']);
                                      }
                                     */
                                }
                                if (isset($tmp['other_field_id'])) {
                                    $fields = $this->Field->read(null, $tmp['field_id']);
                                    if (!in_array($tmp['other_field_id'], explode(",", $fields['Field']['field_value']))) {
                                        $fields['Field']['id'] = $tmp['field_id'];
                                        $fields['Field']['field_value'] = $fields['Field']['field_value'] . "," . $tmp['other_field_id'];
                                        $this->Field->save($fields['Field']);
                                        $this->data['ProductAdditionalFieldValue'][$i]['field_id'] = $tmp['field_id'];
                                        $this->data['ProductAdditionalFieldValue'][$i]['values'] = $tmp['other_field_id'];
                                    }
                                }
                                if (isset($tmp['chk_values'])) {
                                    $this->data['ProductAdditionalFieldValue'][$i]['field_id'] = $tmp['field_id'];
                                    if (is_array($tmp['chk_values']))
                                        $this->data['ProductAdditionalFieldValue'][$i]['values'] = implode(",", $tmp['chk_values']);
                                    else
                                        $this->data['ProductAdditionalFieldValue'][$i]['values'] = $tmp['chk_values'];
                                }

                                $this->data['ProductAdditionalFieldValue'][$i]['product_id'] = $product_id;
                                if (isset($tmp['id'])) {
                                    $this->data['ProductAdditionalFieldValue'][$i]['id'] = $tmp['id'];
                                }
                                $i++;
                            }
                            $this->ProductAdditionalFieldValue->create();
                            $this->ProductAdditionalFieldValue->saveAll($this->data['ProductAdditionalFieldValue']);
                        }

                        //Product sizes
                        if (isset($this->data['ProductSize']) OR isset($this->data['ProductSizeLabel']) OR (isset($this->data['sizearray']) && isset($this->data['valuearray']))) {
                            $i = 0;
                            if (isset($this->data['ProductSize'])) {
                                foreach ($this->data['ProductSize'] as $tmp) {
                                    if (isset($tmp['sizevalue_id'])) {
                                        $this->data['ProductSize'][$i]['product_id'] = $product_id;
                                        $this->data['ProductSize'][$i]['category_id'] = $this->data['Product']['category_id'];
                                        $this->data['ProductSize'][$i]['sizevalue_id'] = $tmp['sizevalue_id'];
                                        $this->data['ProductSize'][$i]['sizetitle_id'] = $tmp['sizetitle_id'];
                                        $this->data['ProductSize'][$i]['sizelabel_id'] = 0;
                                        $i++;
                                    }
                                }
                            }

                            if (isset($this->data['ProductSizeLabel'])) {
                                foreach ($this->data['ProductSizeLabel'] as $tmp) {
                                    if (isset($tmp['sizevalue_id'])) {
                                        $this->data['ProductSize'][$i]['product_id'] = $product_id;
                                        $this->data['ProductSize'][$i]['category_id'] = $this->data['Product']['category_id'];
                                        $this->data['ProductSize'][$i]['sizevalue_id'] = $tmp['sizevalue_id'];
                                        $this->data['ProductSize'][$i]['sizetitle_id'] = $tmp['sizetitle_id'];
                                        $this->data['ProductSize'][$i]['sizelabel_id'] = $tmp['sizelabel_id'];
                                        $i++;
                                    }
                                }
                            }
                            if (isset($this->data['sizearray']) && isset($this->data['valuearray'])) {
                                $this->data['ProductSize'][$i]['product_id'] = $product_id;
                                $this->data['ProductSize'][$i]['category_id'] = $this->data['Product']['category_id'];
                                $this->data['ProductSize'][$i]['sizetitle_id'] = $this->data['sizearray'];
                                $this->data['ProductSize'][$i]['sizevalue_id'] = $this->data['valuearray'];
                                $this->data['ProductSize'][$i]['sizelabel_id'] = 0;
                            }

                            $this->ProductSize->create();
                            $this->ProductSize->saveAll($this->data['ProductSize']);
                        }

                        //Products Shipping Method 
                        if (isset($this->data['ProductShippings'])) {
                            $i = 0;
                            foreach ($this->data['ProductShippings'] as $tmp) {
                                $this->data['ProductShipping'][$i]['product_id'] = $product_id;
                                $this->data['ProductShipping'][$i]['shipping_id'] = $tmp;
                                $i++;
                            }
                            $this->ProductShipping->create();
                            $this->ProductShipping->saveAll($this->data['ProductShipping']);
                        }

                        if ((isset($this->data['Product']['product_international_shipping']) || $this->data['Product']['product_international_shipping'] == 'Yes') && isset($this->data['ProductInternationalShippings'])) {
                            //Products International Shipping Method						
                            $i = 0;
                            foreach ($this->data['ProductInternationalShippings'] as $tmp) {
                                if (isset($tmp['id']))
                                    $this->data['ProductInternationalShipping'][$i]['id'] = $tmp['id'];
                                $this->data['ProductInternationalShipping'][$i]['shipping_id'] = $tmp['shipping_id'];
                                $this->data['ProductInternationalShipping'][$i]['product_id'] = $product_id;

                                if ($tmp['continent_id'] == "custom_location") {
                                    $tmp['continent_id'] = implode(",", $this->data['customlocation']);
                                }

                                $this->data['ProductInternationalShipping'][$i]['continent_id'] = $tmp['continent_id'];
                                $this->data['ProductInternationalShipping'][$i]['shipping_cost'] = $tmp['shipping_cost'];
                                $i++;
                            }

                            $this->ProductInternationalShipping->create();
                            $this->ProductInternationalShipping->saveAll($this->data['ProductInternationalShipping']);
                        }
                        if ($this->Session->check('blockCountry')) {
                            $this->loadModel('Country');
                            $this->loadModel('Continent');
                            $this->loadModel('BlockCountryShip');
                            $block_country = unserialize(base64_decode($this->Session->read('blockCountry')));
                            if (!empty($block_country['country_name'])) {
                                $totalcountry = $this->Country->find('count');
                                for ($i = 0; $i < $totalcountry; $i++) {
                                    if (isset($block_country['country_name'][$i])) {
                                        $str = explode('_', $block_country['country_name'][$i]);
                                        $country = $str[0];
                                        $con = $str[1];
                                        $cunt = $this->BlockCountryShip->find('count', array('conditions' => array('BlockCountryShip.product_id' => $product_id, 'BlockCountryShip.seller_id' => $this->Auth->user('id'), 'BlockCountryShip.continent_id' => $con, 'BlockCountryShip.country_id' => $country)));
                                        if ($cunt < 1) {
                                            $this->data['BlockCountryShip']['id'] = null;
                                            $this->data['BlockCountryShip']['seller_id'] = $this->Auth->user('id');
                                            $this->data['BlockCountryShip']['country_id'] = $country;
                                            $this->data['BlockCountryShip']['continent_id'] = $con;
                                            $this->data['BlockCountryShip']['product_id'] = $product_id;
                                            $this->BlockCountryShip->save($this->data);
                                        }
                                    } else {

                                        $str = explode('_', $block_country['con_name'][$i]);
                                        $country = $str[0];
                                        $con = $str[1];
                                        $cunt = $this->BlockCountryShip->find('count', array('conditions' => array('BlockCountryShip.product_id' => $product_id, 'BlockCountryShip.seller_id' => $this->Auth->user('id'), 'BlockCountryShip.continent_id' => $con, 'BlockCountryShip.country_id' => $country)));

                                        if ($cunt > 0) {
                                            $con = array('BlockCountryShip.product_id' => $product_id, 'BlockCountryShip.seller_id' => $this->Auth->user('id'), 'BlockCountryShip.continent_id' => $con, 'BlockCountryShip.country_id' => $country);
                                            $this->BlockCountryShip->deleteAll($con);
                                        }
                                    }
                                }
                                $this->Session->setFlash(__('The Block countries has been Updated Successfully.', true));
                            } else {
                                $totalcountry = $this->Country->find('count');
                                for ($i = 0; $i < $totalcountry; $i++) {
                                    $str = explode('_', $block_country['con_name'][$i]);
                                    $country = $str[0];
                                    $con = $str[1];
                                    $cunt = $this->BlockCountryShip->find('count', array('conditions' => array('BlockCountryShip.product_id' => $product_id, 'BlockCountryShip.seller_id' => $this->Auth->user('id'), 'BlockCountryShip.continent_id' => $con, 'BlockCountryShip.country_id' => $country)));

                                    if ($cunt > 0) {
                                        $con = array('BlockCountryShip.product_id' => $product_id, 'BlockCountryShip.seller_id' => $this->Auth->user('id'), 'BlockCountryShip.continent_id' => $con, 'BlockCountryShip.country_id' => $country);
                                        $this->BlockCountryShip->deleteAll($con);
                                    }
                                }
                                $this->Session->setFlash(__('The Block countries has been Updated Successfully.', true));
                            }
                            $this->Session->delete('blockCountry');
                        }
                        $this->Session->setFlash(__('The product has been saved', true));
                        $this->redirect(array('action' => 'success'));
                    } else {
                        $this->Session->setFlash(__('The product could not be saved into database. Something went wrong please, try again.', true));
                        $this->redirect(array('action' => 'success'));
                    }
                }
            }
        }
        /*         * *********************Domestic*************************** */
        $this->Shipping->recursive = -1;
        $shippings = $this->Shipping->find("list");

        $this->loadModel('Continent');
        $this->Continent->recursive = -1;
        $internationalocations = $this->Continent->find("list", array("fields" => array("id", "name"), "order" => "name asc"));

        $users = $this->Product->User->find('list');

        $categories = $this->Product->Category->find('list', array(
            'conditions' => array('Category.parent_id' => '0'),
            'order' => 'Category.category_order ASC'));
        $handalingtimes = $this->HandleTime->find('list');

        //check user adding products limit
        if ($this->Auth->user('group_id') == 7) {
            $productLimit = $this->Product->productLimit($this->Auth->user('id'));
            if ($productLimit) {
                $this->Session->setFlash(__('You have excceded(maximum 10 products) your limit to add product. Please contact with the site administrator for further query.', true));
                $limitCross = "Yes";
                $this->set('limitCross', $limitCross);
            }
        }
        $this->set(compact('shippings', 'handalingtimes', 'users', 'categories', 'internationashippings', 'internationalocations', 'productinternationalshippings'));
        $this->set('title_for_layout', 'Add Product');

        $this->set('item', $this->Category->categoryArray());
        $this->loadModel('Paymentmethod');
        $payments = $this->Paymentmethod->find("all");
        $this->data['payments'] = $payments;
    }

    function edit($id = null) {
        $this->layout = "innerhome";
        ///product chk by user
        $user_chk = $this->Product->find('count', array('conditions' => array('Product.user_id' => $this->Auth->user('id'), 'Product.id' => $id)));
        $this->set('user_chk', $user_chk);
        if (!$id && empty($this->data)) {
            $this->set('user_chk', '0');
        }
        if (!empty($this->data)) {
            //$this->data = Sanitize::clean($this->data, array('remove_html' => true));

            if (empty($this->data['Product']['global_brands'])) {
                $this->data['Product']['global_brands'] = 0;
            }
            if (isset($this->data['Product']['sugestbrands']) AND empty($this->data['Product']['global_brands'])) {
                $this->data['Brand']['brand_type'] = "brand";
                $this->data['Brand']['brand_description'] = $this->data['Product']['sugestbrands'];
                $this->Brand->create();
                $this->Brand->save($this->data['Brand']);
                $brand_id = $this->Brand->getlastinsertid();
                $this->data['Categorybrand']['brand_type'] = "brand";
                $this->data['Categorybrand']['brand_id'] = $brand_id;
                $this->data['Categorybrand']['category_id'] = $this->data['Product']['category_id'];
                $this->Categorybrand->create();
                $this->Categorybrand->save($this->data['Categorybrand']);
                $this->data['Product']['global_brands'] = $brand_id;
            }

            if (empty($this->data['Product']['global_styles'])) {
                $this->data['Product']['global_styles'] = 0;
            }
            //if user suggested new style
            if (isset($this->data['Product']['sugeststyles']) AND empty($this->data['Product']['global_styles'])) {
                $this->data['Brand']['brand_type'] = "style";
                $this->data['Brand']['brand_description'] = $this->data['Product']['sugeststyles'];
                $this->Brand->create();
                $this->Brand->save($this->data['Brand']);
                $style_id = $this->Brand->getlastinsertid();
                $this->data['Categorybrand']['brand_type'] = "style";
                $this->data['Categorybrand']['brand_id'] = $style_id;
                $this->data['Categorybrand']['category_id'] = $this->data['Product']['category_id'];
                $this->Categorybrand->create();
                $this->Categorybrand->save($this->data['Categorybrand']);
                $this->data['Product']['global_styles'] = $style_id;
            }
            if (empty($this->data['Product']['global_conditions'])) {
                $this->data['Product']['global_conditions'] = 0;
            }
            //if user suggested new condition
            if (isset($this->data['Product']['sugestconditions']) AND empty($this->data['Product']['global_conditions'])) {
                $this->data['Brand']['brand_type'] = "condition";
                $this->data['Brand']['brand_description'] = $this->data['Product']['sugestconditions'];
                $this->Brand->create();
                $this->Brand->save($this->data['Brand']);
                $condition_id = $this->Brand->getlastinsertid();

                $this->data['Categorybrand']['brand_type'] = "condition";
                $this->data['Categorybrand']['brand_id'] = $condition_id;
                $this->data['Categorybrand']['category_id'] = $this->data['Product']['category_id'];
                $this->Categorybrand->create();
                $this->Categorybrand->save($this->data['Categorybrand']);
                $this->data['Product']['global_conditions'] = $condition_id;
            }
            $product_id = $this->data['Product']['id'];
            //uploading products image then add products
            if ($image_data = $this->Uploader->uploadAll()) {
                if (isset($image_data['fileName']['name']))
                    $this->data['Product']['products_thumbnailImage'] = $image_data['fileName']['name'];
                unset($image_data['fileName']);

                $cat_id = $this->data['Product']['category_id'];
                $i = 1;
                if ($this->data['ProductImage']) {
                    foreach ($this->data['ProductImage'] as $key => $val) {
                        if (isset($image_data['fileName' . $key])) {
                            $this->data['ProductImage']['image'] = $image_data['fileName' . $key]['name'];
                            if (isset($val['required'])) {
                                $this->data['ProductImage']['required'] = $val['required'];
                            }
                            $this->data['ProductImage']['product_id'] = $product_id;
                            $this->data['ProductImage']['category_id'] = $cat_id;
                            if (isset($val['id'])) {
                                $this->data['ProductImage']['id'] = $val['id'];
                            } else {
                                $this->ProductImage->create();
                            }
                            $this->ProductImage->save($this->data['ProductImage']);
                        }
                        $i++;
                    }
                }
            }
            if (isset($this->data['AdditionalFieldValue'])) {
                //Additional Fields 
                $i = 0;
                foreach ($this->data['AdditionalFieldValue'] as $tmp) {
                    if (isset($tmp['values'])) {
                        $this->data['ProductAdditionalFieldValue'][$i]['field_id'] = $tmp['field_id'];
                        $this->data['ProductAdditionalFieldValue'][$i]['values'] = $tmp['values'];
                        /*
                          if(isset($tmp['values'])){
                          $options['fields']=array("Field.field_value");
                          $options['conditions']=array("Field.id"=>$tmp['field_id']);
                          $fields=$this->Field->find('first',$options);
                          $dropdown_values=explode(",",$fields['Field']['field_value']);
                          } */
                    }
                    if (isset($tmp['other_field_id'])) {
                        $fields = $this->Field->read(null, $tmp['field_id']);
                        if (!in_array($tmp['other_field_id'], explode(",", $fields['Field']['field_value']))) {
                            $fields['Field']['id'] = $tmp['field_id'];
                            $fields['Field']['field_value'] = $fields['Field']['field_value'] . "," . $tmp['other_field_id'];
                            $this->Field->save($fields['Field']);
                            $this->data['ProductAdditionalFieldValue'][$i]['field_id'] = $tmp['field_id'];
                            $this->data['ProductAdditionalFieldValue'][$i]['values'] = $tmp['other_field_id'];
                        }
                    }
                    if (isset($tmp['chk_values'])) {
                        $this->data['ProductAdditionalFieldValue'][$i]['field_id'] = $tmp['field_id'];
                        if (is_array($tmp['chk_values']))
                            $this->data['ProductAdditionalFieldValue'][$i]['values'] = implode(",", $tmp['chk_values']);
                        else
                            $this->data['ProductAdditionalFieldValue'][$i]['values'] = $tmp['chk_values'];
                    }
                    $this->data['ProductAdditionalFieldValue'][$i]['product_id'] = $this->data['Product']['id'];
                    if (isset($tmp['id'])) {
                        $this->data['ProductAdditionalFieldValue'][$i]['id'] = $tmp['id'];
                    }
                    $i++;
                }
                $this->ProductAdditionalFieldValue->create();
                $this->ProductAdditionalFieldValue->saveAll($this->data['ProductAdditionalFieldValue']);
            }

            if ($this->Session->Check('Auth.User.group_id') == 3) {
                $this->Session->setFlash(__('Product has been successfully updated and listed under product listing page.', 'flash_success'));
                $this->data['Product']['products_status'] = "Approved";
            } else {
                $this->Session->setFlash(__('This page will go to the Q admin if the following features change. If any from Block 2, block 3 (except gallery image), Block 4, the product page will go back to Q admin for approval.', 'flash_success'));

                if ($this->data['Product']['productchange'] == 1)
                    $this->data['Product']['products_status'] = "Pending";
            }


            if ($this->Product->save($this->data)) {
                if (isset($this->data['ProductSize']) OR isset($this->data['ProductSizeLabel']) OR (isset($this->data['sizearray']) && isset($this->data['valuearray']))) {
                    //Product sizes
                    $i = 0;
                    if (isset($this->data['ProductSize'])) {
                        foreach ($this->data['ProductSize'] as $tmp) {
                            if (isset($tmp['sizevalue_id'])) {
                                $this->data['ProductSize'][$i]['product_id'] = $this->data['Product']['id'];
                                $this->data['ProductSize'][$i]['category_id'] = $this->data['Product']['category_id'];
                                $this->data['ProductSize'][$i]['sizevalue_id'] = $tmp['sizevalue_id'];
                                $this->data['ProductSize'][$i]['sizetitle_id'] = $tmp['sizetitle_id'];
                                $this->data['ProductSize'][$i]['sizelabel_id'] = 0;
                                if (isset($tmp['id'])) {
                                    $this->data['ProductSize'][$i]['id'] = $tmp['id'];
                                }
                                $i++;
                            }
                        }
                    }
                    if (isset($this->data['ProductSizeLabel'])) {
                        foreach ($this->data['ProductSizeLabel'] as $tmp) {
                            if (isset($tmp['sizevalue_id'])) {
                                $this->data['ProductSize'][$i]['product_id'] = $product_id;
                                $this->data['ProductSize'][$i]['category_id'] = $this->data['Product']['category_id'];
                                $this->data['ProductSize'][$i]['sizevalue_id'] = $tmp['sizevalue_id'];
                                $this->data['ProductSize'][$i]['sizetitle_id'] = $tmp['sizetitle_id'];
                                $this->data['ProductSize'][$i]['sizelabel_id'] = $tmp['sizelabel_id'];
                                if (isset($tmp['id'])) {
                                    $this->data['ProductSize'][$i]['id'] = $tmp['id'];
                                }
                                $i++;
                            }
                        }
                    }
                    if (isset($this->data['sizearray']) && isset($this->data['valuearray'])) {
                        if (isset($this->data['productsizeid']))
                            $this->data['ProductSize'][$i]['id'] = $this->data['productsizeid'];
                        $this->data['ProductSize'][$i]['product_id'] = $this->data['Product']['id'];
                        $this->data['ProductSize'][$i]['category_id'] = $this->data['Product']['category_id'];
                        $this->data['ProductSize'][$i]['sizetitle_id'] = $this->data['sizearray'];
                        $this->data['ProductSize'][$i]['sizevalue_id'] = $this->data['valuearray'];
                        $this->data['ProductSize'][$i]['sizelabel_id'] = 0;
                    }
                    $this->ProductSize->create();
                    $this->ProductSize->saveAll($this->data['ProductSize']);
                }

                if (isset($this->data['ProductShippings'])) {
                    //Products Shipping Method 
                    $i = 0;
                    foreach ($this->data['ProductShippings'] as $tmp) {
                        $this->data['ProductShipping'][$i]['product_id'] = $product_id;
                        $this->data['ProductShipping'][$i]['shipping_id'] = $tmp['shipping_id'];
                        if (isset($tmp['id']))
                            $this->data['ProductShipping'][$i]['id'] = $tmp['id'];
                        $i++;
                    }
                    $this->ProductShipping->create();
                    $this->ProductShipping->saveAll($this->data['ProductShipping']);
                }

                if ((isset($this->data['Product']['product_international_shipping']) || $this->data['Product']['product_international_shipping'] == 'Yes') && isset($this->data['ProductInternationalShippings'])) {
                    //Products International Shipping Method
                    $i = 0;
                    foreach ($this->data['ProductInternationalShippings'] as $tmp) {
                        if (isset($tmp['id']))
                            $this->data['ProductInternationalShipping'][$i]['id'] = $tmp['id'];
                        $this->data['ProductInternationalShipping'][$i]['shipping_id'] = $tmp['shipping_id'];
                        $this->data['ProductInternationalShipping'][$i]['product_id'] = $product_id;
                        if ($tmp['continent_id'] == "custom_location") {
                            $tmp['continent_id'] = implode(",", $this->data['customlocation']);
                        }
                        $this->data['ProductInternationalShipping'][$i]['continent_id'] = $tmp['continent_id'];
                        $this->data['ProductInternationalShipping'][$i]['shipping_cost'] = $tmp['shipping_cost'];
                        $i++;
                    }
                    $this->ProductInternationalShipping->create();
                    $this->ProductInternationalShipping->saveAll($this->data['ProductInternationalShipping']);
                }

                if ($this->Session->check('blockCountry')) {
                    $this->loadModel('Country');
                    $this->loadModel('Continent');
                    $this->loadModel('BlockCountryShip');
                    $block_country = unserialize(base64_decode($this->Session->read('blockCountry')));
                    if (!empty($block_country['country_name'])) {
                        $totalcountry = $this->Country->find('count');
                        for ($i = 0; $i < $totalcountry; $i++) {

                            if (isset($block_country['country_name'][$i])) {
                                $str = explode('_', $block_country['country_name'][$i]);
                                $country = $str[0];
                                $con = $str[1];
                                $cunt = $this->BlockCountryShip->find('count', array('conditions' => array('BlockCountryShip.product_id' => $product_id, 'BlockCountryShip.seller_id' => $this->Auth->user('id'), 'BlockCountryShip.continent_id' => $con, 'BlockCountryShip.country_id' => $country)));
                                if ($cunt < 1) {
                                    $this->data['BlockCountryShip']['id'] = null;
                                    $this->data['BlockCountryShip']['seller_id'] = $this->Auth->user('id');
                                    $this->data['BlockCountryShip']['country_id'] = $country;
                                    $this->data['BlockCountryShip']['continent_id'] = $con;
                                    $this->data['BlockCountryShip']['product_id'] = $product_id;
                                    $this->BlockCountryShip->save($this->data);
                                }
                            } else {

                                $str = explode('_', $block_country['con_name'][$i]);
                                $country = $str[0];
                                $con = $str[1];
                                $cunt = $this->BlockCountryShip->find('count', array('conditions' => array('BlockCountryShip.product_id' => $product_id, 'BlockCountryShip.seller_id' => $this->Auth->user('id'), 'BlockCountryShip.continent_id' => $con, 'BlockCountryShip.country_id' => $country)));

                                if ($cunt > 0) {
                                    $con = array('BlockCountryShip.product_id' => $product_id, 'BlockCountryShip.seller_id' => $this->Auth->user('id'), 'BlockCountryShip.continent_id' => $con, 'BlockCountryShip.country_id' => $country);
                                    $this->BlockCountryShip->deleteAll($con);
                                }
                            }
                        }
                        $this->Session->setFlash(__('The Block countries has been Updated Successfully.', true));
                    } else {
                        $totalcountry = $this->Country->find('count');
                        for ($i = 0; $i < $totalcountry; $i++) {
                            $str = explode('_', $block_country['con_name'][$i]);
                            $country = $str[0];
                            $con = $str[1];
                            $cunt = $this->BlockCountryShip->find('count', array('conditions' => array('BlockCountryShip.product_id' => $product_id, 'BlockCountryShip.seller_id' => $this->Auth->user('id'), 'BlockCountryShip.continent_id' => $con, 'BlockCountryShip.country_id' => $country)));

                            if ($cunt > 0) {
                                $con = array('BlockCountryShip.product_id' => $product_id, 'BlockCountryShip.seller_id' => $this->Auth->user('id'), 'BlockCountryShip.continent_id' => $con, 'BlockCountryShip.country_id' => $country);
                                $this->BlockCountryShip->deleteAll($con);
                            }
                        }

                        $this->Session->setFlash(__('The Block countries has been Updated Successfully.', true));
                    }
                    $this->Session->delete('blockCountry');
                }
                $this->redirect(array('action' => 'success'));
            } else {
                $this->Session->setFlash(__('The product could not be saved.  Something went wrong please, try again.', true));
                $this->redirect(array('action' => 'success'));
            }
        }
        if (empty($this->data)) {
            $this->Product->recursive = 0;
            $this->data = $this->Product->read(null, $id);
            if (!$this->data['Product']) {
                $this->set('user_chk', '0');
            }
            $this->data['ProductShippings'] = $this->ProductShipping->find('all', array('conditions' => array('ProductShipping.product_id' => $id)));

            $this->ProductInternationalShipping->unbindModel(array('belongsTo' => array('Continent')));
            $productinternationalshippings = $this->ProductInternationalShipping->find('all', array('conditions' => array('ProductInternationalShipping.product_id' => $id)));
            $i = 0;
            $this->loadModel("Continent");
            $this->Continent->recursive = -1;
            foreach ($productinternationalshippings as $productinternationalshipping):
                if ($productinternationalshipping['ProductInternationalShipping']['continent_id'] != "worldwide") {
                    $conID = explode(",", $productinternationalshipping['ProductInternationalShipping']['continent_id']);
                    $flag = 1;
                    $continent = "";
                    foreach ($conID as $continentID) {
                        $continent_name = $this->Continent->find("first", array("conditions" => array("id" => $continentID), "fields" => array("name")));
                        if ($flag == 1) {
                            $continent.=$continent_name['Continent']['name'];
                            $flag = 0;
                        }
                        else
                            $continent.=", " . $continent_name['Continent']['name'];
                    }
                    $productinternationalshippings[$i]['ProductInternationalShipping']['continent_id'] = $continent;
                }
                else
                    $productinternationalshippings[$i]['ProductInternationalShipping']['continent_id'] = $productinternationalshipping['ProductInternationalShipping']['continent_id'];
                $i++;
            endforeach;
            $subcat = $this->chkHasParent($this->data['Product']['category_id']);
            $bredcrumb = '<p><em>*</em> Current category: <span>';
            $this->Category->recursive = -1;
            if (isset($subcat['catid_label2'])) {
                $catid_label2 = $this->Category->findById($subcat['catid_label2']);
                $bredcrumb.=$catid_label2['Category']['category_name'];
            }
            if (isset($subcat['catid_label3'])) {
                $catid_label3 = $this->Category->findById($subcat['catid_label3']);
                $bredcrumb.=" >> " . $catid_label3['Category']['category_name'];
            }
            if (isset($subcat['catid_label4'])) {
                $catid_label4 = $this->Category->findById($subcat['catid_label4']);
                $bredcrumb.=" >> " . $catid_label4['Category']['category_name'];
            }
            if (isset($subcat['catid_label5'])) {
                $catid_label5 = $this->Category->findById($subcat['catid_label5']);
                $bredcrumb.=" >> " . $catid_label5['Category']['category_name'];
            }
            $bredcrumb.='</span></p>';
            $this->data['bredcrumb'] = $bredcrumb;
            $this->data['subcat'] = $subcat;
        }
        $users = $this->Product->User->find('list');
        $categories = $this->Product->Category->find('list', array(
            'conditions' => array('Category.parent_id' => '0'),
            'order' => 'Category.category_order ASC'));
        $this->Shipping->recursive = -1;
        $shippings = $this->Shipping->find("list");
        $handalingtimes = $this->HandleTime->find("list");
        $this->set(compact('shippings', 'handalingtimes'));
        $this->Country->recursive = -1;
        $this->loadModel("Continent");
        $internationalocations = $this->Continent->find("list", array("fields" => array("id", "name"), "order" => "Continent.name asc"));
        $this->set(compact('users', 'categories', 'internationalocations', 'productinternationalshippings'));
    }

    function sell_similar($id = null) {
        $this->layout = "innerhome";
        ///product chk by user
        $user_chk = $this->Product->find('count', array('conditions' => array('Product.user_id' => $this->Auth->user('id'), 'Product.id' => $id)));
        $this->set('user_chk', $user_chk);
        if (!$id && empty($this->data)) {
            $this->set('user_chk', '0');
        }
        if (!empty($this->data)) {
            //$this->data = Sanitize::clean($this->data, array('remove_html' => true));
            $this->Product->set($this->data);
            if ($this->Product->validates()) {
                if (isset($this->data['Product']['sugestbrands']) && ($this->data['Product']['sugestbrands'] == "Enter Brand")) {
                    $this->data['Product']['global_brands'] = 0;
                }
                //if user suggested new brand
                if (isset($this->data['Product']['sugestbrands']) && empty($this->data['Product']['global_brands'])) {
                    $this->data['Brand']['brand_type'] = "brand";
                    $this->data['Brand']['brand_description'] = $this->data['Product']['sugestbrands'];
                    $this->Brand->create();
                    $this->Brand->save($this->data['Brand']);
                    $brand_id = $this->Brand->getlastinsertid();
                    $this->data['Categorybrand']['brand_type'] = "brand";
                    $this->data['Categorybrand']['brand_id'] = $brand_id;
                    $this->data['Categorybrand']['category_id'] = $this->data['Product']['category_id'];
                    $this->Categorybrand->create();
                    $this->Categorybrand->save($this->data['Categorybrand']);
                    $this->data['Product']['global_brands'] = $brand_id;
                }
                if (isset($this->data['Product']['sugeststyles']) && ($this->data['Product']['sugeststyles'] == "Enter Style")) {
                    $this->data['Product']['global_styles'] = 0;
                }
                //if user suggested new style
                if (isset($this->data['Product']['sugeststyles']) && empty($this->data['Product']['global_styles'])) {
                    $this->data['Brand']['brand_type'] = "style";
                    $this->data['Brand']['brand_description'] = $this->data['Product']['sugeststyles'];
                    $this->Brand->create();
                    $this->Brand->save($this->data['Brand']);
                    $style_id = $this->Brand->getlastinsertid();
                    $this->data['Categorybrand']['brand_type'] = "style";
                    $this->data['Categorybrand']['brand_id'] = $style_id;
                    $this->data['Categorybrand']['category_id'] = $this->data['Product']['category_id'];
                    $this->Categorybrand->create();
                    $this->Categorybrand->save($this->data['Categorybrand']);
                    $this->data['Product']['global_styles'] = $style_id;
                }
                if (isset($this->data['Product']['sugestconditions']) && ($this->data['Product']['sugestconditions'] == "Enter Condition")) {
                    $this->data['Product']['global_conditions'] = 0;
                }
                //if user suggested new condition
                if (isset($this->data['Product']['sugestconditions']) && empty($this->data['Product']['global_conditions'])) {
                    $this->data['Brand']['brand_type'] = "condition";
                    $this->data['Brand']['brand_description'] = $this->data['Product']['sugestconditions'];
                    $this->Brand->create();
                    $this->Brand->save($this->data['Brand']);
                    $condition_id = $this->Brand->getlastinsertid();
                    $this->data['Categorybrand']['brand_type'] = "condition";
                    $this->data['Categorybrand']['brand_id'] = $condition_id;
                    $this->data['Categorybrand']['category_id'] = $this->data['Product']['category_id'];
                    $this->Categorybrand->create();
                    $this->Categorybrand->save($this->data['Categorybrand']);
                    $this->data['Product']['global_conditions'] = $condition_id;
                }
                $this->data['Product']['products_createDate'] = date("Y-m-d H:s:i");
                $nextWeek = strtotime("+1 week");
                $this->data['Product']['products_expiredDate'] = date("Y-m-d H:s:i", $nextWeek);
                if ($image_data = $this->Uploader->uploadAll()) {
                    if (isset($image_data['fileName']['name']))
                        $this->data['Product']['products_thumbnailImage'] = $image_data['fileName']['name'];
                }

                if ($this->Session->Check('Auth.User.group_id') == 3) {
                    $this->data['Product']['products_status'] = "Approved";
                    $this->Session->setFlash(__('Product has been successfully added and listed under product listing page.', true));
                } else {
                    $this->data['Product']['products_status'] = "Pending";
                    $this->Session->setFlash(__('Product has been added successfully.', true));
                }

                $this->Product->create();
                if ($this->Product->save($this->data)) {
                    $product_id = $this->Product->getlastinsertid();
                    unset($image_data['fileName']);
                    $cat_id = $this->data['cat_id'];
                    $i = 1;

                    if ($image_data) {
                        foreach ($image_data as $key => $val) {
                            if ($val['name']) {
                                $this->data['ProductImage'][$i]['image'] = $val['name'];
                                $this->data['ProductImage'][$i]['product_id'] = $product_id;
                                $this->data['ProductImage'][$i]['category_id'] = $cat_id;
                                $i++;
                            }
                        }
                        if (isset($this->data['ProductImage'])) {
                            $this->ProductImage->create();
                            $this->ProductImage->saveAll($this->data['ProductImage']);
                        }
                    }

                    //Additional Fields
                    if (isset($this->data['AdditionalFieldValue'])) {
                        $i = 0;
                        foreach ($this->data['AdditionalFieldValue'] as $tmp) {
                            if (isset($tmp['values'])) {
                                $this->data['ProductAdditionalFieldValue'][$i]['field_id'] = $tmp['field_id'];
                                $this->data['ProductAdditionalFieldValue'][$i]['values'] = $tmp['values'];
                                /*
                                  if(isset($tmp['values'])){
                                  $options['fields']=array("Field.field_value");
                                  $options['conditions']=array("Field.id"=>$tmp['field_id']);
                                  $fields=$this->Field->find('first',$options);
                                  $dropdown_values=explode(",",$fields['Field']['field_value']);
                                  } */
                            }
                            if (isset($tmp['other_field_id'])) {
                                $fields = $this->Field->read(null, $tmp['field_id']);
                                if (!in_array($tmp['other_field_id'], explode(",", $fields['Field']['field_value']))) {
                                    $fields['Field']['id'] = $tmp['field_id'];
                                    $fields['Field']['field_value'] = $fields['Field']['field_value'] . "," . $tmp['other_field_id'];
                                    $this->Field->save($fields['Field']);
                                    $this->data['ProductAdditionalFieldValue'][$i]['field_id'] = $tmp['field_id'];
                                    $this->data['ProductAdditionalFieldValue'][$i]['values'] = $tmp['other_field_id'];
                                }
                            }
                            if (isset($tmp['chk_values'])) {
                                $this->data['ProductAdditionalFieldValue'][$i]['field_id'] = $tmp['field_id'];
                                if (is_array($tmp['chk_values']))
                                    $this->data['ProductAdditionalFieldValue'][$i]['values'] = implode(",", $tmp['chk_values']);
                                else
                                    $this->data['ProductAdditionalFieldValue'][$i]['values'] = $tmp['chk_values'];
                            }
                            $this->data['ProductAdditionalFieldValue'][$i]['product_id'] = $product_id;
                            $i++;
                        }
                        $this->ProductAdditionalFieldValue->create();
                        $this->ProductAdditionalFieldValue->saveAll($this->data['ProductAdditionalFieldValue']);
                    }
                    //Product sizes
                    if (isset($this->data['ProductSize']) OR isset($this->data['ProductSizeLabel']) OR (isset($this->data['sizearray']) && isset($this->data['valuearray']))) {
                        //Product sizes
                        $i = 0;
                        if (isset($this->data['ProductSize'])) {
                            foreach ($this->data['ProductSize'] as $tmp) {
                                if (isset($tmp['sizevalue_id'])) {
                                    $this->data['ProductSize'][$i]['product_id'] = $this->data['Product']['id'];
                                    $this->data['ProductSize'][$i]['category_id'] = $this->data['Product']['category_id'];
                                    $this->data['ProductSize'][$i]['sizevalue_id'] = $tmp['sizevalue_id'];
                                    $this->data['ProductSize'][$i]['sizetitle_id'] = $tmp['sizetitle_id'];
                                    $this->data['ProductSize'][$i]['sizelabel_id'] = 0;
                                    if (isset($tmp['id'])) {
                                        $this->data['ProductSize'][$i]['id'] = $tmp['id'];
                                    }
                                    $i++;
                                }
                            }
                        }
                        if (isset($this->data['ProductSizeLabel'])) {
                            foreach ($this->data['ProductSizeLabel'] as $tmp) {
                                if (isset($tmp['sizevalue_id'])) {
                                    $this->data['ProductSize'][$i]['product_id'] = $product_id;
                                    $this->data['ProductSize'][$i]['category_id'] = $this->data['Product']['category_id'];
                                    $this->data['ProductSize'][$i]['sizevalue_id'] = $tmp['sizevalue_id'];
                                    $this->data['ProductSize'][$i]['sizetitle_id'] = $tmp['sizetitle_id'];
                                    $this->data['ProductSize'][$i]['sizelabel_id'] = $tmp['sizelabel_id'];
                                    if (isset($tmp['id'])) {
                                        $this->data['ProductSize'][$i]['id'] = $tmp['id'];
                                    }
                                    $i++;
                                }
                            }
                        }
                        if (isset($this->data['sizearray']) && isset($this->data['valuearray'])) {
                            if (isset($this->data['productsizeid']))
                                $this->data['ProductSize'][$i]['id'] = $this->data['productsizeid'];
                            $this->data['ProductSize'][$i]['product_id'] = $this->data['Product']['id'];
                            $this->data['ProductSize'][$i]['category_id'] = $this->data['Product']['category_id'];
                            $this->data['ProductSize'][$i]['sizetitle_id'] = $this->data['sizearray'];
                            $this->data['ProductSize'][$i]['sizevalue_id'] = $this->data['valuearray'];
                            $this->data['ProductSize'][$i]['sizelabel_id'] = 0;
                        }
                        $this->ProductSize->create();
                        $this->ProductSize->saveAll($this->data['ProductSize']);
                    }
                    //Products Shipping Method 
                    $this->ProductShipping->recursive = -1;
                    $domestic_shippings = $this->ProductShipping->find("all", array("conditions" => array("ProductShipping.product_id" => $this->data['Product']['pid'])));
                    $i = 0;
                    if ($domestic_shippings) {
                        foreach ($domestic_shippings as $domestic_shipping) {
                            $this->data['ProductShippings'][$i]['product_id'] = $product_id;
                            $this->data['ProductShippings'][$i]['shipping_id'] = $domestic_shipping['ProductShipping']['shipping_id'];
                            $i++;
                        }
                    }
                    if (isset($this->data['ProductShippings'])) {
                        foreach ($this->data['ProductShippings'] as $tmp) {
                            $this->data['ProductShipping'][$i]['product_id'] = $product_id;
                            $this->data['ProductShipping'][$i]['shipping_id'] = $tmp['shipping_id'];
                            $i++;
                        }
                        $this->ProductShipping->create();
                        $this->ProductShipping->saveAll($this->data['ProductShipping']);
                    }

                    $this->ProductInternationalShipping->recursive = -1;
                    $international_shippings = $this->ProductInternationalShipping->find("all", array("conditions" => array("ProductInternationalShipping.product_id" => $this->data['Product']['pid'])));
                    $i = 0;
                    if ($international_shippings) {
                        foreach ($international_shippings as $international_shipping) {
                            $this->data['ProductInternationalShippings'][$i]['shipping_id'] = $international_shipping['ProductInternationalShipping']['shipping_id'];
                            $this->data['ProductInternationalShippings'][$i]['product_id'] = $product_id;
                            $this->data['ProductInternationalShippings'][$i]['continent_id'] = $international_shipping['ProductInternationalShipping']['continent_id'];
                            $this->data['ProductInternationalShippings'][$i]['shipping_cost'] = $international_shipping['ProductInternationalShipping']['shipping_cost'];
                            $i++;
                        }
                    }
                    if ((isset($this->data['Product']['product_international_shipping']) || $this->data['Product']['product_international_shipping'] == 'Yes') && isset($this->data['ProductInternationalShippings'])) {
                        foreach ($this->data['ProductInternationalShippings'] as $tmp) {
                            $this->data['ProductInternationalShipping'][$i]['shipping_id'] = $tmp['shipping_id'];
                            $this->data['ProductInternationalShipping'][$i]['product_id'] = $product_id;
                            if ($tmp['continent_id'] == "custom_location") {
                                $tmp['continent_id'] = implode(",", $this->data['customlocation']);
                            }
                            $this->data['ProductInternationalShipping'][$i]['continent_id'] = $tmp['continent_id'];
                            $this->data['ProductInternationalShipping'][$i]['shipping_cost'] = $tmp['shipping_cost'];
                            $i++;
                        }
                        $this->ProductInternationalShipping->create();
                        $this->ProductInternationalShipping->saveAll($this->data['ProductInternationalShipping']);
                    }
                    if ($this->Session->check('blockCountry')) {
                        $this->loadModel('Country');
                        $this->loadModel('Continent');
                        $this->loadModel('BlockCountryShip');
                        $block_country = unserialize(base64_decode($this->Session->read('blockCountry')));
                        if (!empty($block_country['country_name'])) {
                            $totalcountry = $this->Country->find('count');
                            for ($i = 0; $i < $totalcountry; $i++) {
                                if (isset($block_country['country_name'][$i])) {
                                    $str = explode('_', $block_country['country_name'][$i]);
                                    $country = $str[0];
                                    $con = $str[1];
                                    $cunt = $this->BlockCountryShip->find('count', array('conditions' => array('BlockCountryShip.product_id' => $product_id, 'BlockCountryShip.seller_id' => $this->Auth->user('id'), 'BlockCountryShip.continent_id' => $con, 'BlockCountryShip.country_id' => $country)));
                                    if ($cunt < 1) {
                                        $this->data['BlockCountryShip']['id'] = null;
                                        $this->data['BlockCountryShip']['seller_id'] = $this->Auth->user('id');
                                        $this->data['BlockCountryShip']['country_id'] = $country;
                                        $this->data['BlockCountryShip']['continent_id'] = $con;
                                        $this->data['BlockCountryShip']['product_id'] = $product_id;
                                        $this->BlockCountryShip->save($this->data);
                                    }
                                } else {
                                    $str = explode('_', $block_country['con_name'][$i]);
                                    $country = $str[0];
                                    $con = $str[1];
                                    $cunt = $this->BlockCountryShip->find('count', array('conditions' => array('BlockCountryShip.product_id' => $product_id, 'BlockCountryShip.seller_id' => $this->Auth->user('id'), 'BlockCountryShip.continent_id' => $con, 'BlockCountryShip.country_id' => $country)));
                                    if ($cunt > 0) {
                                        $con = array('BlockCountryShip.product_id' => $product_id, 'BlockCountryShip.seller_id' => $this->Auth->user('id'), 'BlockCountryShip.continent_id' => $con, 'BlockCountryShip.country_id' => $country);
                                        $this->BlockCountryShip->deleteAll($con);
                                    }
                                }
                            }
                            $this->Session->setFlash(__('The Block countries has been Updated Successfully.', true));
                        } else {
                            $totalcountry = $this->Country->find('count');
                            for ($i = 0; $i < $totalcountry; $i++) {
                                $str = explode('_', $block_country['con_name'][$i]);
                                $country = $str[0];
                                $con = $str[1];
                                $cunt = $this->BlockCountryShip->find('count', array('conditions' => array('BlockCountryShip.product_id' => $product_id, 'BlockCountryShip.seller_id' => $this->Auth->user('id'), 'BlockCountryShip.continent_id' => $con, 'BlockCountryShip.country_id' => $country)));
                                if ($cunt > 0) {
                                    $con = array('BlockCountryShip.product_id' => $product_id, 'BlockCountryShip.seller_id' => $this->Auth->user('id'), 'BlockCountryShip.continent_id' => $con, 'BlockCountryShip.country_id' => $country);
                                    $this->BlockCountryShip->deleteAll($con);
                                }
                            }
                            $this->Session->setFlash(__('The Block countries has been Updated Successfully.', true));
                        }
                        $this->Session->delete('blockCountry');
                    }

                    $this->redirect(array('action' => 'success'));
                } else {
                    $this->Session->setFlash(__('The product could not be saved. Something went wrong please, try again.', true));
                    $this->redirect(array('action' => 'success'));
                }
            }
        }
        if (empty($this->data)) {
            $this->Product->recursive = 0;
            $this->data = $this->Product->read(null, $id);
            if (!$this->data['Product']) {
                $this->Session->setFlash(__('Invalid product ID', true));
                $this->redirect(array('action' => 'success'));
            }
            $this->data['ProductShippings'] = $this->ProductShipping->find('all', array('conditions' => array('ProductShipping.product_id' => $id)));
            $this->ProductInternationalShipping->unbindModel(array('belongsTo' => array('Continent')));
            $productinternationalshippings = $this->ProductInternationalShipping->find('all', array('conditions' => array('ProductInternationalShipping.product_id' => $id)));
            $i = 0;
            $this->loadModel("Continent");
            $this->Continent->recursive = -1;
            foreach ($productinternationalshippings as $productinternationalshipping):
                if ($productinternationalshipping['ProductInternationalShipping']['continent_id'] != "worldwide") {
                    $conID = explode(",", $productinternationalshipping['ProductInternationalShipping']['continent_id']);
                    $flag = 1;
                    $continent = "";
                    foreach ($conID as $continentID) {
                        $continent_name = $this->Continent->find("first", array("conditions" => array("id" => $continentID), "fields" => array("name")));
                        if ($flag == 1) {
                            $continent.=$continent_name['Continent']['name'];
                            $flag = 0;
                        }
                        else
                            $continent.=", " . $continent_name['Continent']['name'];
                    }
                    $productinternationalshippings[$i]['ProductInternationalShipping']['continent_id'] = $continent;
                }
                else
                    $productinternationalshippings[$i]['ProductInternationalShipping']['continent_id'] = $productinternationalshipping['ProductInternationalShipping']['continent_id'];
                $i++;
            endforeach;

            $subcat = $this->chkHasParent($this->data['Product']['category_id']);
            $bredcrumb = '<p><em>*</em> Current category: <span>';
            $this->Category->recursive = -1;
            if (isset($subcat['catid_label2'])) {
                $catid_label2 = $this->Category->findById($subcat['catid_label2']);
                $bredcrumb.=$catid_label2['Category']['category_name'];
            }
            if (isset($subcat['catid_label3'])) {
                $catid_label3 = $this->Category->findById($subcat['catid_label3']);
                $bredcrumb.=" >> " . $catid_label3['Category']['category_name'];
            }
            if (isset($subcat['catid_label4'])) {
                $catid_label4 = $this->Category->findById($subcat['catid_label4']);
                $bredcrumb.=" >> " . $catid_label4['Category']['category_name'];
            }
            if (isset($subcat['catid_label5'])) {
                $catid_label5 = $this->Category->findById($subcat['catid_label5']);
                $bredcrumb.=" >> " . $catid_label5['Category']['category_name'];
            }
            $bredcrumb.='</span></p>';
            $this->data['bredcrumb'] = $bredcrumb;
            $this->data['subcat'] = $subcat;
        }
        $users = $this->Product->User->find('list');
        $categories = $this->Product->Category->find('list', array(
            'conditions' => array('Category.parent_id' => '0'),
            'order' => 'Category.category_order ASC'));
        $this->Shipping->recursive = -1;
        $shippings = $this->Shipping->find("list");
        $handalingtimes = $this->HandleTime->find("list");
        $this->set(compact('shippings', 'handalingtimes'));
        $this->Country->recursive = -1;
        $this->loadModel("Continent");
        $internationalocations = $this->Continent->find("list", array("fields" => array("id", "name"), "order" => "Continent.name asc"));
        $this->set(compact('users', 'categories', 'internationashippings', 'internationalocations', 'productinternationalshippings'));
    }

    function chkduplicatefield($id = null, $id2=null) {
        $this->layout = false;
        $return_array['fid'] = $id;
        $this->data = $this->Field->read(null, $id);
        if (!in_array($id2, explode(",", $this->data['Field']['field_value'])))
            $return_array['message'] = "This value is available";
        else
            $return_array['message'] = "<b style='color:red'>Duplicate value. Plaese try another.</b>";
        echo json_encode($return_array);
        $this->autoRender = false;
    }

    function international_cost($id=null) {
        $this->layout = false;
        $this->loadModel("ProductInternationalShipping");
        $international_cost = $this->ProductInternationalShipping->find("all");
        echo json_encode($international_cost);
        $this->autoRender = false;
    }

    function unsold() {
        $this->Product->Behaviors->attach('Containable');
        if (!empty($this->data['keywords']) AND $this->data['search_by'] == 'item_title') {
            $this->paginate = array('limit' => 25, 'contain' => array('Note'), 'conditions' => array('Product.products_title LIKE' => '%' . $this->data['keywords'] . '%', 'Product.user_id' => $this->Auth->User('id'), 'Product.products_status' => 'Unsold'), 'order' => array('Product.id' => 'desc'));
        } elseif (!empty($this->data['keywords']) AND $this->data['search_by'] == 'item_number') {
            $this->paginate = array('limit' => 25, 'contain' => array('Note'), 'conditions' => array('Product.id' => $this->data['keywords'], 'Product.user_id' => $this->Auth->User('id'), 'Product.products_status' => 'Unsold'), 'order' => array('Product.id' => 'desc'));
        } else {
            $this->paginate = array('limit' => 25, 'contain' => array('Note'), 'conditions' => array('Product.user_id' => $this->Auth->User('id'), 'Product.products_status' => 'Unsold'), 'order' => array('Product.id' => 'desc'));
        }

        $this->set('products', $this->paginate());
        $this->layout = "innerhome";
    }

    function pending() {
        $this->Product->Behaviors->attach('Containable');
        if (!empty($this->data['keywords']) AND $this->data['search_by'] == 'item_title') {
            $this->paginate = array('limit' => 25, 'contain' => array('Note'), 'conditions' => array('Product.products_title LIKE' => '%' . $this->data['keywords'] . '%', 'Product.user_id' => $this->Auth->User('id'), 'Product.products_status' => 'Pending'), 'order' => array('Product.id' => 'desc'));
        } elseif (!empty($this->data['keywords']) AND $this->data['search_by'] == 'item_number') {
            $this->paginate = array('limit' => 25, 'contain' => array('Note'), 'conditions' => array('Product.id' => $this->data['keywords'], 'Product.user_id' => $this->Auth->User('id'), 'Product.products_status' => 'Pending'), 'order' => array('Product.id' => 'desc'));
        } else {
            $this->paginate = array('limit' => 25, 'contain' => array('Note'), 'conditions' => array('Product.user_id' => $this->Auth->User('id'), 'Product.products_status' => 'Pending'), 'order' => array('Product.id' => 'desc'));
        }

        $this->set('products', $this->paginate());
        $this->layout = "innerhome";
    }

    function disapproved() {
        $this->Product->recursive = -1;
        if (!empty($this->data['keywords']) AND $this->data['search_by'] == 'item_title') {
            $this->paginate = array('limit' => 25, 'conditions' => array('Product.products_title LIKE' => '%' . $this->data['keywords'] . '%', 'Product.user_id' => $this->Auth->User('id'), 'Product.products_status' => 'Disapproved'), 'order' => array('Product.id' => 'desc'));
        } elseif (!empty($this->data['keywords']) AND $this->data['search_by'] == 'item_number') {
            $this->paginate = array('limit' => 25, 'conditions' => array('Product.id' => $this->data['keywords'], 'Product.user_id' => $this->Auth->User('id'), 'Product.products_status' => 'Disapproved'), 'order' => array('Product.id' => 'desc'));
        } else {
            $this->paginate = array('limit' => 25, 'conditions' => array('Product.user_id' => $this->Auth->User('id'), 'Product.products_status' => 'Disapproved'), 'order' => array('Product.id' => 'desc'));
        }

        $this->set('products', $this->paginate());
        $this->layout = "innerhome";
    }

    function backstage_ptrack_approved($serchkey=null, $type=null) {
        $this->Product->recursive = 1;
        $this->Product->Behaviors->attach('Containable');
        /* if($this->Session->read('grouptype')!='S-Admins'){

          $this->loadModel('BrandPermission');

          $bids=$this->BrandPermission->findAllByUserId($this->Auth->User('id'),array('brand_id'));

          if(!empty($bids)){
          foreach($bids as $bid){
          $brandids[]=$bid['BrandPermission']['brand_id'];
          }

          $this->Product->contain('User.username');

          if(!empty($_POST['serchkey'])){
          $type=$this->data['type'];
          $serchkey=$_POST['serchkey'];
          $this->set('type',$type);
          $this->set('serchkey',$serchkey);
          }else{
          $this->set('type',$type);
          $this->set('serchkey',$serchkey);
          }

          if($serchkey!=null){
          if ($type == 'item') {
          /////////////////////////

          $this->paginate = array('limit' => 25,
          'conditions'=>array('OR'=>array('Product.global_brands'=> $brandids,
          'Product.global_styles'=> $brandids,
          'Product.global_conditions'=> $brandids),
          'OR'=>array(array('Product.products_status' => 'Approved'),array('Product.products_status' => 'Active')),
          'Product.id'=> $serchkey),
          'order' => array('Product.id' => 'desc'),
          'fields'=>array('Product.id','Product.products_thumbnailImage','Product.products_title','Product.user_id','Product.approved_id','Product.approved_date','Product.products_status'),
          'contain'=>array(
          'User.username',
          'Approver.username'
          )
          );
          //////////////////////
          }
          if ($type == 'title') {
          /////////////////////////
          $this->paginate = array('limit' => 25,
          'conditions'=>array('OR'=>array('Product.global_brands'=> $brandids,
          'Product.global_styles'=> $brandids,
          'Product.global_conditions'=> $brandids),
          'OR'=>array(array('Product.products_status' => 'Approved'),array('Product.products_status' => 'Active')),
          'Product.products_title like' => '%' .$serchkey.'%'),
          'order' => array('Product.id' => 'desc'),
          'fields'=>array('Product.id','Product.products_thumbnailImage','Product.products_title','Product.user_id','Product.approved_id','Product.approved_date','Product.products_status'),
          'contain'=>array(
          'User.username',
          'Approver.username'
          )
          );
          //////////////////////
          }
          if ($type == 'sellerid') {
          /////////////////////////

          $this->paginate = array('limit' => 25,
          'conditions'=>array('OR'=>array('Product.global_brands'=> $brandids,
          'Product.global_styles'=> $brandids,
          'Product.global_conditions'=> $brandids),
          'OR'=>array(array('Product.products_status' => 'Approved'),array('Product.products_status' => 'Active')),
          'User.username'=> $serchkey),
          'order' => array('Product.id' => 'desc'),
          'fields'=>array('Product.id','Product.products_thumbnailImage','Product.products_title','Product.user_id','Product.approved_id','Product.approved_date','Product.products_status'),
          'contain'=>array(
          'User.username',
          'Approver.username'
          )
          );
          //////////////////////
          }
          }else{
          $this->paginate = array('limit' => 25,
          'conditions'=>array('OR'=>array('Product.global_brands'=> $brandids,
          'Product.global_styles'=> $brandids,
          'Product.global_conditions'=> $brandids),
          'OR'=>array(array('Product.products_status' => 'Approved'),array('Product.products_status' => 'Active')),
          'order' => array('Product.id' => 'desc'),
          'fields'=>array('Product.id','Product.products_thumbnailImage','Product.products_title','Product.user_id','Product.approved_id','Product.approved_date','Product.products_status'),
          'contain'=>array(
          'User.username',
          'Approver.username'
          )
          );
          }
          $this->set('products', $this->paginate());
          }else{
          $this->set('products', '');
          }

          }else{ */
        //////////For Super Admin/////
        $this->Product->contain('User.username');
        if (!empty($_POST['serchkey'])) {
            $type = $this->data['type'];
            $serchkey = $_POST['serchkey'];
            $this->set('type', $type);
            $this->set('serchkey', $serchkey);
        } else {
            $this->set('type', $type);
            $this->set('serchkey', $serchkey);
        }
        if ($serchkey != null) {
            if ($type == 'item') {
                $this->paginate = array('limit' => 25,
                    'conditions' => array(
                        'OR' => array(array('Product.products_status' => 'Approved'), array('Product.products_status' => 'Active')),
                        'Product.id' => $serchkey),
                    'order' => array('Product.id' => 'desc'),
                    'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.approved_date', 'Product.products_status'),
                    'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
                );
            }
            if ($type == 'title') {
                $this->paginate = array('limit' => 25,
                    'conditions' => array(
                        'OR' => array(array('Product.products_status' => 'Approved'), array('Product.products_status' => 'Active')),
                        'Product.products_title like' => '%' . $serchkey . '%'),
                    'order' => array('Product.id' => 'desc'),
                    'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.approved_date', 'Product.products_status'),
                    'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
                );
            }
            if ($type == 'sellerid') {
                $this->paginate = array('limit' => 25,
                    'conditions' => array(
                        'OR' => array(array('Product.products_status' => 'Approved'), array('Product.products_status' => 'Active')),
                        'User.username' => $serchkey),
                    'order' => array('Product.id' => 'desc'),
                    'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.approved_date', 'Product.products_status'),
                    'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
                );
            }
        } else {
            $this->paginate = array('limit' => 25,
                'conditions' => array(
                    'OR' => array(array('Product.products_status' => 'Approved'), array('Product.products_status' => 'Active'))),
                'order' => array('Product.id' => 'desc'),
                'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.approved_date', 'Product.products_status'),
                'contain' => array(
                    'User.username',
                    'Approver.username'
                )
            );
        }
        $this->set('products', $this->paginate());
        $this->layout = "admin";
    }

    function backstage_featured($serchkey=null, $type=null) {
        $this->Product->recursive = 1;
        $this->Product->Behaviors->attach('Containable');
        /* if($this->Session->read('grouptype')!='S-Admins'){

          $this->loadModel('BrandPermission');

          $bids=$this->BrandPermission->findAllByUserId($this->Auth->User('id'),array('brand_id'));

          if(!empty($bids)){
          foreach($bids as $bid){
          $brandids[]=$bid['BrandPermission']['brand_id'];
          }

          $this->Product->contain('User.username');

          if(!empty($_POST['serchkey'])){
          $type=$this->data['type'];
          $serchkey=$_POST['serchkey'];
          $this->set('type',$type);
          $this->set('serchkey',$serchkey);
          }else{
          $this->set('type',$type);
          $this->set('serchkey',$serchkey);
          }

          if($serchkey!=null){
          if ($type == 'item') {
          /////////////////////////

          $this->paginate = array('limit' => 25,
          'conditions'=>array('OR'=>array('Product.global_brands'=> $brandids,
          'Product.global_styles'=> $brandids,
          'Product.global_conditions'=> $brandids),
          'OR'=>array(array('Product.products_status' => 'Approved'),array('Product.products_status' => 'Active')),
          'Product.id'=> $serchkey),
          'order' => array('Product.id' => 'desc'),
          'fields'=>array('Product.id','Product.products_thumbnailImage','Product.products_title','Product.user_id','Product.approved_id','Product.approved_date','Product.products_status'),
          'contain'=>array(
          'User.username',
          'Approver.username'
          )
          );
          //////////////////////
          }
          if ($type == 'title') {
          /////////////////////////
          $this->paginate = array('limit' => 25,
          'conditions'=>array('OR'=>array('Product.global_brands'=> $brandids,
          'Product.global_styles'=> $brandids,
          'Product.global_conditions'=> $brandids),
          'OR'=>array(array('Product.products_status' => 'Approved'),array('Product.products_status' => 'Active')),
          'Product.products_title like' => '%' .$serchkey.'%'),
          'order' => array('Product.id' => 'desc'),
          'fields'=>array('Product.id','Product.products_thumbnailImage','Product.products_title','Product.user_id','Product.approved_id','Product.approved_date','Product.products_status'),
          'contain'=>array(
          'User.username',
          'Approver.username'
          )
          );
          //////////////////////
          }
          if ($type == 'sellerid') {
          /////////////////////////

          $this->paginate = array('limit' => 25,
          'conditions'=>array('OR'=>array('Product.global_brands'=> $brandids,
          'Product.global_styles'=> $brandids,
          'Product.global_conditions'=> $brandids),
          'OR'=>array(array('Product.products_status' => 'Approved'),array('Product.products_status' => 'Active')),
          'User.username'=> $serchkey),
          'order' => array('Product.id' => 'desc'),
          'fields'=>array('Product.id','Product.products_thumbnailImage','Product.products_title','Product.user_id','Product.approved_id','Product.approved_date','Product.products_status'),
          'contain'=>array(
          'User.username',
          'Approver.username'
          )
          );
          //////////////////////
          }
          }else{
          $this->paginate = array('limit' => 25,
          'conditions'=>array('OR'=>array('Product.global_brands'=> $brandids,
          'Product.global_styles'=> $brandids,
          'Product.global_conditions'=> $brandids),
          'OR'=>array(array('Product.products_status' => 'Approved'),array('Product.products_status' => 'Active')),
          'order' => array('Product.id' => 'desc'),
          'fields'=>array('Product.id','Product.products_thumbnailImage','Product.products_title','Product.user_id','Product.approved_id','Product.approved_date','Product.products_status'),
          'contain'=>array(
          'User.username',
          'Approver.username'
          )
          );
          }
          $this->set('products', $this->paginate());
          }else{
          $this->set('products', '');
          }

          }else{ */
        //////////For Super Admin/////
        $this->Product->contain('User.username');
        if (!empty($_POST['serchkey'])) {
            $type = $this->data['type'];
            $serchkey = $_POST['serchkey'];
            $this->set('type', $type);
            $this->set('serchkey', $serchkey);
        } else {
            $this->set('type', $type);
            $this->set('serchkey', $serchkey);
        }
        if ($serchkey != null) {
            if ($type == 'item') {
                $this->paginate = array('limit' => 25,
                    'conditions' => array(
                        'OR' => array(array('Product.products_status' => 'Approved'), array('Product.products_status' => 'Active')),
                        'OR' => array(array('Product.featured' => 'Yes'), array('Product.featured' => 'Pending')),
                        'Product.id' => $serchkey),
                    'order' => array('Product.id' => 'desc'),
                    'fields' => array('Product.featured', 'Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.approved_date', 'Product.products_status'),
                    'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
                );
            }
            if ($type == 'title') {
                $this->paginate = array('limit' => 25,
                    'conditions' => array(
                        'OR' => array(array('Product.products_status' => 'Approved'), array('Product.products_status' => 'Active')),
                        'OR' => array(array('Product.featured' => 'Yes'), array('Product.featured' => 'Pending')),
                        'Product.products_title like' => '%' . $serchkey . '%'),
                    'order' => array('Product.id' => 'desc'),
                    'fields' => array('Product.featured', 'Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.approved_date', 'Product.products_status'),
                    'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
                );
            }
            if ($type == 'sellerid') {
                $this->paginate = array('limit' => 25,
                    'conditions' => array(
                        'OR' => array(array('Product.products_status' => 'Approved'), array('Product.products_status' => 'Active')),
                        'OR' => array(array('Product.featured' => 'Yes'), array('Product.featured' => 'Pending')),
                        'User.username' => $serchkey),
                    'order' => array('Product.id' => 'desc'),
                    'fields' => array('Product.featured', 'Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.approved_date', 'Product.products_status'),
                    'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
                );
            }
        } else {
            $this->paginate = array('limit' => 25,
                'conditions' => array(
                    'OR' => array(array('Product.products_status' => 'Approved'), array('Product.products_status' => 'Active')),
                    'OR' => array(array('Product.featured' => 'Yes'), array('Product.featured' => 'Pending'))),
                'order' => array('Product.id' => 'desc'),
                'fields' => array('Product.featured', 'Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.approved_date', 'Product.products_status'),
                'contain' => array(
                    'User.username',
                    'Approver.username'
                )
            );
        }
        $this->set('products', $this->paginate());
        $this->layout = "admin";
    }

    function backstage_ptrack_pending($serchkey=null, $type=null) {
        $this->Product->recursive = 1;
        $this->Product->Behaviors->attach('Containable');
        /* if ($this->Session->read('grouptype') != 'S-Admins') {
          $this->loadModel('BrandPermission');
          $bids = $this->BrandPermission->findAllByUserId($this->Auth->User('id'), array('brand_id'));
          if (!empty($bids)) {
          foreach ($bids as $bid) {
          $brandids[] = $bid['BrandPermission']['brand_id'];
          }
          $this->Product->contain('User.username');
          if (!empty($_POST['serchkey'])) {
          $type = $this->data['type'];
          $serchkey = $_POST['serchkey'];
          $this->set('type', $type);
          $this->set('serchkey', $serchkey);
          } else {
          $this->set('type', $type);
          $this->set('serchkey', $serchkey);
          }
          if ($serchkey != null) {
          if ($type == 'item') {
          $this->paginate = array('limit' => 25,
          'conditions' => array('OR' => array('Product.global_brands' => $brandids,
          'Product.global_styles' => $brandids,
          'Product.global_conditions' => $brandids),
          'Product.products_status' => 'Pending',
          'Product.id' => $serchkey),
          'order' => array('Product.id' => 'desc'),
          'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.products_createDate', 'Product.products_status'),
          'contain' => array(
          'User.username',
          'Approver.username'
          )
          );
          }
          if ($type == 'title') {
          $this->paginate = array('limit' => 25,
          'conditions' => array('OR' => array('Product.global_brands' => $brandids,
          'Product.global_styles' => $brandids,
          'Product.global_conditions' => $brandids),
          'Product.products_status' => 'Pending',
          'Product.products_title like' => '%' . $serchkey . '%'),
          'order' => array('Product.id' => 'desc'),
          'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.products_createDate', 'Product.products_status'),
          'contain' => array(
          'User.username',
          'Approver.username'
          )
          );
          }
          if ($type == 'sellerid') {
          $this->paginate = array('limit' => 25,
          'conditions' => array('OR' => array('Product.global_brands' => $brandids,
          'Product.global_styles' => $brandids,
          'Product.global_conditions' => $brandids),
          'Product.products_status' => 'Pending',
          'User.username' => $serchkey),
          'order' => array('Product.id' => 'desc'),
          'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.products_createDate', 'Product.products_status'),
          'contain' => array(
          'User.username',
          'Approver.username'
          )
          );
          }
          } else {
          $this->paginate = array('limit' => 25,
          'conditions' => array('OR' => array('Product.global_brands' => $brandids,
          'Product.global_styles' => $brandids,
          'Product.global_conditions' => $brandids),
          'Product.products_status' => 'Pending'),
          'order' => array('Product.id' => 'desc'),
          'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.products_createDate', 'Product.products_status'),
          'contain' => array(
          'User.username',
          'Approver.username'
          )
          );
          }
          $this->set('products', $this->paginate());
          } else {
          $this->set('products', '');
          }
          } else { */
        /////////for super admin//////////
        $this->Product->contain('User.username');
        if (!empty($_POST['serchkey'])) {
            $type = $this->data['type'];
            $serchkey = $_POST['serchkey'];
            $this->set('type', $type);
            $this->set('serchkey', $serchkey);
        } else {
            $this->set('type', $type);
            $this->set('serchkey', $serchkey);
        }
        if ($serchkey != null) {
            if ($type == 'item') {
                $this->paginate = array('limit' => 25,
                    'conditions' => array(
                        'Product.products_status' => 'Pending',
                        'Product.id' => $serchkey),
                    'order' => array('Product.id' => 'desc'),
                    'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.products_createDate', 'Product.products_status'),
                    'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
                );
            }
            if ($type == 'title') {
                $this->paginate = array('limit' => 25,
                    'conditions' => array(
                        'Product.products_status' => 'Pending',
                        'Product.products_title like' => '%' . $serchkey . '%'),
                    'order' => array('Product.id' => 'desc'),
                    'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.products_createDate', 'Product.products_status'),
                    'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
                );
            }
            if ($type == 'sellerid') {
                $this->paginate = array('limit' => 25,
                    'conditions' => array(
                        'Product.products_status' => 'Pending',
                        'User.username' => $serchkey),
                    'order' => array('Product.id' => 'desc'),
                    'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.products_createDate', 'Product.products_status'),
                    'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
                );
            }
        } else {
            $this->paginate = array('limit' => 25,
                'conditions' => array(
                    'Product.products_status' => 'Pending'),
                'order' => array('Product.id' => 'desc'),
                'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.products_createDate', 'Product.products_status'),
                'contain' => array(
                    'User.username',
                    'Approver.username'
                )
            );
        }
        $this->set('products', $this->paginate());
        //}
        $this->layout = "admin";
    }

    function backstage_ptrack_disapproved($serchkey=null, $type=null) {
        $this->Product->recursive = 1;
        $this->Product->Behaviors->attach('Containable');
        /* if ($this->Session->read('grouptype') != 'S-Admins') {
          $this->loadModel('BrandPermission');
          $bids = $this->BrandPermission->findAllByUserId($this->Auth->User('id'), array('brand_id'));
          if (!empty($bids)) {
          foreach ($bids as $bid) {
          $brandids[] = $bid['BrandPermission']['brand_id'];
          }
          $this->Product->contain('User.username');
          if (!empty($_POST['serchkey'])) {
          $type = $this->data['type'];
          $serchkey = $_POST['serchkey'];
          $this->set('type', $type);
          $this->set('serchkey', $serchkey);
          } else {
          $this->set('type', $type);
          $this->set('serchkey', $serchkey);
          }
          if ($serchkey != null) {
          if ($type == 'item') {
          $this->paginate = array('limit' => 25,
          'conditions' => array('OR' => array('Product.global_brands' => $brandids,
          'Product.global_styles' => $brandids,
          'Product.global_conditions' => $brandids),
          'Product.products_status' => 'Disapproved',
          'Product.id' => $serchkey),
          'order' => array('Product.id' => 'desc'),
          'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.disapproved_date', 'Product.products_status'),
          'contain' => array(
          'User.username',
          'Approver.username'
          )
          );
          }
          if ($type == 'title') {
          $this->paginate = array('limit' => 25,
          'conditions' => array('OR' => array('Product.global_brands' => $brandids,
          'Product.global_styles' => $brandids,
          'Product.global_conditions' => $brandids),
          'Product.products_status' => 'Disapproved',
          'Product.products_title like' => '%' . $serchkey . '%'),
          'order' => array('Product.id' => 'desc'),
          'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.disapproved_date', 'Product.products_status'),
          'contain' => array(
          'User.username',
          'Approver.username'
          )
          );
          }
          if ($type == 'sellerid') {
          $this->paginate = array('limit' => 25,
          'conditions' => array('OR' => array('Product.global_brands' => $brandids,
          'Product.global_styles' => $brandids,
          'Product.global_conditions' => $brandids),
          'Product.products_status' => 'Disapproved',
          'User.username' => $serchkey),
          'order' => array('Product.id' => 'desc'),
          'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.disapproved_date', 'Product.products_status'),
          'contain' => array(
          'User.username',
          'Approver.username'
          )
          );
          }
          } else {
          $this->paginate = array('limit' => 25,
          'conditions' => array('OR' => array('Product.global_brands' => $brandids,
          'Product.global_styles' => $brandids,
          'Product.global_conditions' => $brandids),
          'Product.products_status' => 'Disapproved'),
          'order' => array('Product.id' => 'desc'),
          'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.disapproved_date', 'Product.products_status'),
          'contain' => array(
          'User.username',
          'Approver.username'
          )
          );
          }
          $this->set('products', $this->paginate());
          } else {
          $this->set('products', '');
          }
          } else { */
        $this->Product->contain('User.username');
        if (!empty($_POST['serchkey'])) {
            $type = $this->data['type'];
            $serchkey = $_POST['serchkey'];
            $this->set('type', $type);
            $this->set('serchkey', $serchkey);
        } else {
            $this->set('type', $type);
            $this->set('serchkey', $serchkey);
        }
        if ($serchkey != null) {
            if ($type == 'item') {
                $this->paginate = array('limit' => 25,
                    'conditions' => array(
                        'Product.products_status' => 'Disapproved',
                        'Product.id' => $serchkey),
                    'order' => array('Product.id' => 'desc'),
                    'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.disapproved_date', 'Product.products_status'),
                    'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
                );
            }
            if ($type == 'title') {
                $this->paginate = array('limit' => 25,
                    'conditions' => array(
                        'Product.products_status' => 'Disapproved',
                        'Product.products_title like' => '%' . $serchkey . '%'),
                    'order' => array('Product.id' => 'desc'),
                    'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.disapproved_date', 'Product.products_status'),
                    'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
                );
            }
            if ($type == 'sellerid') {
                $this->paginate = array('limit' => 25,
                    'conditions' => array(
                        'Product.products_status' => 'Disapproved',
                        'User.username' => $serchkey),
                    'order' => array('Product.id' => 'desc'),
                    'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.disapproved_date', 'Product.products_status'),
                    'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
                );
            }
        } else {
            $this->paginate = array('limit' => 25,
                'conditions' => array(
                    'Product.products_status' => 'Disapproved'),
                'order' => array('Product.id' => 'desc'),
                'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.disapproved_date', 'Product.products_status'),
                'contain' => array(
                    'User.username',
                    'Approver.username'
                )
            );
        }
        $this->set('products', $this->paginate());
        ///}
        $this->layout = "admin";
    }

    function view_comment($id = null) {
        $this->Product->Behaviors->attach('Containable');
        $this->Product->contain('User.username', 'Approver.username');
        $this->set('product', $this->Product->read(array('Product.id', 'Product.disapprove_comments'), $id));
        $this->layout = false;
    }

    function view($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid product', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->set('product', $this->Product->read(null, $id));
        $this->layout = "innerhome";
    }

    //fetch images
    function fetchimages($id=null, $id2=null) {
        $this->layout = false;
        if (!$id2) {
            $this->Imagetitle->recursive = -1;
            $imagetitles = $this->Imagetitle->find('all', array(
                'conditions' => array('Imagetitle.category_id' => $id),
                'order' => 'Imagetitle.id ASC'));
        } else {
            $conditions = array('ProductImage.product_id' => $id2, 'ProductImage.category_id' => $id);
            $imagetitles = $this->ProductImage->find("all", array('conditions' => $conditions));
            if (count($imagetitles) < 1) {
                $imagetitles = $this->Imagetitle->find('all', array(
                    'conditions' => array('Imagetitle.category_id' => $id),
                    'order' => 'Imagetitle.id ASC'));
            }
        }
        $this->data['cat_id'] = $id;
        $this->set(compact('imagetitles'));
    }

    //fetch sub category
    function fetchSubCategory($id=null, $id2=null) {
        $this->layout = false;
        $categories = $this->Category->fetchSubCategory($id);
        $this->set(compact('categories'));
        $this->data['cat_id'] = $id;
        $this->data['selected_id'] = $id2;
    }

    function fetchParentCategory($id=null) {
        $this->layout = false;
        $categories = $this->Category->fetchParentCategory($id);
        $this->set(compact('categories'));
        if ($id)
            $this->data['cat_id'] = $id;
    }

    function fetchbrand($id=null, $id2=null) {
        $this->layout = false;
        $categorybrands = $this->Categorybrand->fetchbrand($id, $id2);
        $this->set(compact('categorybrands'));
        $this->data['sel_id'] = $id2;
    }

    function fetchstyle($id=null, $id2=null) {
        $this->layout = false;
        $categorybrands = $this->Categorybrand->fetchstyle($id, $id2);
        $this->set(compact('categorybrands'));
        $this->data['sel_id'] = $id2;
    }

    function fetchcondition($id=null, $id2=null) {
        $this->layout = false;
        $categorybrands = $this->Categorybrand->fetchcondition($id, $id2);
        $this->set(compact('categorybrands'));
        $this->data['sel_id'] = $id2;
    }

    function findParentsId($id=null) {
        $this->layout = false;
        return $this->Category->findParentsId($id);
    }

    function checkHasFields($id=null, $id2=null, $pid=null) {
        $this->layout = false;
        $this->Field->recursive = -1;
        $cat_id = $id;
        $options['order'] = array('Field.id' => 'asc');
        $options['conditions'] = array('Field.category_id' => $cat_id);
        if ($this->Field->find('count', $options) > 0) {
            $this->loadModel("Label");
            $labels = $this->Field->Label->find('all', array("conditions" => array("Label.category_id" => $cat_id), "order" => "Label.id ASC"));
            $i = 0;
            foreach ($labels as $label) {
                $options['conditions'] = array('Field.category_id' => $cat_id, 'Field.label_id' => $label['Label']['id']);
                $labels[$i]['hasfield'] = $this->Field->find('count', $options);
                $i++;
            }

            $this->set(compact('labels', 'cat_id', 'pid'));
            return true;
        }else
            return false;
    }

    function fetchadditionalfields_details_label($id=null, $id2=null) {
        $this->layout = false;
        if (!$this->checkHasFields($id, "", $id2)) {
            $parentId = $this->findParentsId($id);
            if (!$this->checkHasFields($parentId, 'No', $id2)) {
                $parentId = $this->findParentsId($parentId);
                if (!$this->checkHasFields($parentId, 'No', $id2)) {
                    $parentId = $this->findParentsId($parentId);
                    $this->checkHasFields($parentId, 'No', $id2);
                }
            }
        }
    }

    function fetchadditionalfields_details($id=null, $id2=null) {
        $this->layout = false;
        if (!$this->checkHasFields($id, "", $id2)) {
            $parentId = $this->findParentsId($id);
            if (!$this->checkHasFields($parentId, 'No', $id2)) {
                $parentId = $this->findParentsId($parentId);
                if (!$this->checkHasFields($parentId, 'No', $id2)) {
                    $parentId = $this->findParentsId($parentId);
                    $this->checkHasFields($parentId, 'No', $id2);
                }
            }
        }
    }

    function fetchadditionalfields($id=null, $id2=null) {
        $this->layout = false;
        if (!$this->checkHasFields($id, "", $id2)) {
            $parentId = $this->findParentsId($id);
            if (!$this->checkHasFields($parentId, 'No', $id2)) {
                $parentId = $this->findParentsId($parentId);
                if (!$this->checkHasFields($parentId, 'No', $id2)) {
                    $parentId = $this->findParentsId($parentId);
                    $this->checkHasFields($parentId, 'No', $id2);
                }
            }
        }
    }

    function fetch_labels_fields_details($id=null, $id2=null, $id3=null) {
        $fields = $this->Field->fetch_labels_fields_details($id, $id2, $id3);
        $this->set(compact('fields'));
    }

    function fetch_labels_fields($id=null, $id2=null, $id3=null) {
        $fields = $this->Field->fetch_labels_fields($id, $id2, $id3);
        $this->set(compact('fields'));
    }

    function fetchsizes($id=null) {
        $this->layout = false;
        $this->Category->bindModel(array('hasMany' => array('Sizelabel' => array(
                    'className' => 'Sizelabel',
                    'foreignKey' => 'category_id'))));
        $options['conditions'] = array('Category.id' => $id);
        $this->Category->Behaviors->attach('Containable');
        $this->Category->contain('Sizelabel', 'Sizetitle', 'Sizetitle.Sizevalue');
        $this->data['category_sizes'] = $this->Category->find('all', $options);
    }

    function fetchsizes_edit($id=null, $id2=null) {
        $this->layout = false;
        $this->Category->bindModel(array('hasMany' => array('Sizelabel' => array(
                    'className' => 'Sizelabel',
                    'foreignKey' => 'category_id'))));
        $options['conditions'] = array('Category.id' => $id);
        $this->Category->Behaviors->attach('Containable');
        $this->Category->contain('Sizelabel', 'Sizetitle', 'Sizetitle.Sizevalue');
        $this->data['category_sizes'] = $this->Category->find('all', $options);

        $options['conditions'] = array('Sizetitle.category_id' => $id);
        $options['order'] = array('Sizetitle.id asc');
        $this->data['Size'] = $this->Sizetitle->find('all', $options);

        $options['conditions'] = array('Sizelabel.category_id' => $id);
        $options['order'] = array('Sizelabel.id asc');
        $this->data['Sizelabel'] = $this->Sizelabel->find('all', $options);
        if (!empty($id2)) {
            $options['conditions'] = array('ProductSize.product_id' => $id2, 'ProductSize.category_id' => $id);
            $options['fields'] = array('ProductSize.id', 'ProductSize.sizevalue_id', 'ProductSize.sizetitle_id', 'ProductSize.sizelabel_id', 'ProductSize.category_id');
            $options['order'] = array('Sizetitle.id asc');
            $this->data['selected_size'] = $this->ProductSize->find('all', $options);
        }
    }

    function chkHasParent($id=null) {
        $this->Category->recursive = -1;
        $parent_id = $this->Category->findById($id, array('parent_id'));
        if ($parent_id['Category']['parent_id'] > 0) {
            $parent_id_label2 = $this->Category->findById($parent_id['Category']['parent_id'], array('parent_id'));
            $subcat['label2'] = "Yes";
            $subcat['label3'] = "No";
            $subcat['label4'] = "No";
            $subcat['catid_label2'] = $parent_id['Category']['parent_id'];
            $subcat['catid_label3'] = $id;

            if ($parent_id_label2['Category']['parent_id'] > 0) {
                $parent_id_label3 = $this->Category->findById($parent_id_label2['Category']['parent_id'], array('parent_id'));
                $subcat['label2'] = "Yes";
                $subcat['label3'] = "Yes";
                $subcat['label4'] = "No";
                $subcat['catid_label2'] = $parent_id_label2['Category']['parent_id'];
                $subcat['catid_label3'] = $parent_id['Category']['parent_id'];
                $subcat['catid_label4'] = $id;
            }
            if (isset($parent_id_label3['Category']['parent_id']) && $parent_id_label3['Category']['parent_id'] > 0) {
                $parent_id_label4 = $this->Category->findById($parent_id_label3['Category']['parent_id'], array('parent_id'));
                $subcat['label2'] = "Yes";
                $subcat['label3'] = "Yes";
                $subcat['label4'] = "Yes";
                $subcat['catid_label2'] = $parent_id_label3['Category']['parent_id'];
                $subcat['catid_label3'] = $parent_id_label2['Category']['parent_id'];
                $subcat['catid_label4'] = $parent_id['Category']['parent_id'];
                $subcat['catid_label5'] = $id;
            }
        } else {
            $subcat['label2'] = "No";
            $subcat['label3'] = "No";
            $subcat['label4'] = "No";
            $subcat['catid_label2'] = $id;
        }
        return $subcat;
    }

    function breadcrumchkHasParent($id=null) {
        $this->layout = null;
        $this->autoRender = false;
        $this->Category->recursive = -1;
        $parent_id = $this->Category->findById($id, array('parent_id', 'category_name'));
        if ($parent_id['Category']['parent_id'] > 0) {
            $parent_id_label2 = $this->Category->findById($parent_id['Category']['parent_id'], array('parent_id', 'category_name'));
            $subcat['label'] = "2";
            $subcat['catname_label1'] = $parent_id_label2['Category']['category_name'];
            $subcat['catid_label1'] = $parent_id['Category']['parent_id'];
            $subcat['catname_label2'] = $parent_id['Category']['category_name'];
            $subcat['catid_label2'] = $id;
            if ($parent_id_label2['Category']['parent_id'] > 0) {
                $parent_id_label3 = $this->Category->findById($parent_id_label2['Category']['parent_id'], array('parent_id', 'category_name'));
                $subcat['label'] = "3";
                $subcat['catname_label1'] = $parent_id_label3['Category']['category_name'];
                $subcat['catid_label1'] = $parent_id_label2['Category']['parent_id'];
                $subcat['catname_label2'] = $parent_id_label2['Category']['category_name'];
                $subcat['catid_label2'] = $parent_id['Category']['parent_id'];
                $subcat['catname_label3'] = $parent_id['Category']['category_name'];
                $subcat['catid_label3'] = $id;
            }
            if (isset($parent_id_label3['Category']['parent_id']) && $parent_id_label3['Category']['parent_id'] > 0) {
                $parent_id_label4 = $this->Category->findById($parent_id_label3['Category']['parent_id'], array('parent_id', 'category_name'));
                $subcat['label'] = "4";
                $subcat['catname_label1'] = $parent_id_label4['Category']['category_name'];
                $subcat['catid_label1'] = $parent_id_label3['Category']['parent_id'];
                $subcat['catname_label2'] = $parent_id_label3['Category']['category_name'];
                $subcat['catid_label2'] = $parent_id_label2['Category']['parent_id'];
                $subcat['catname_label3'] = $parent_id_label2['Category']['category_name'];
                $subcat['catid_label3'] = $parent_id['Category']['parent_id'];
                $subcat['catname_label4'] = $parent_id['Category']['category_name'];
                $subcat['catid_label4'] = $id;
            }
        } else {
            $subcat['label'] = "1";
            $subcat['catname_label1'] = $parent_id['Category']['category_name'];
            $subcat['catid_label1'] = $id;
        }
        return $subcat;
    }

    function fetchshippingmethod($id = null, $id2 = null) {
        $this->layout = false;
        $this->Shipping->recursive = -1;
        $shippings = $this->Shipping->find("all", array("conditions" => array("Shipping.category_id" => $id, "shipping_destination" => "National")));
        $handalingtimes = $this->HandleTime->find("all");
        $this->set(compact('shippings', 'handalingtimes'));
        $this->data['selected_handletime'] = "0";
        if (!empty($id2)) {
            $this->data['ProductShippings'] = $this->ProductShipping->find('all', array('conditions' => array('ProductShipping.product_id' => $id2)));
            $this->Product->recursive = -1;
            $productshippings = $this->Product->find('first', array('fields' => array('handletime_id', 'handale_additional_info'), 'conditions' => array('Product.id' => $id2)));
            $this->data['selected_handletime'] = $productshippings['Product']['handletime_id'];
            $this->data['handale_additional_info'] = $productshippings['Product']['handale_additional_info'];
        }
    }

    function getshippingcost($id = null) {
        $this->layout = false;
        $this->Category->recursive = -1;
        $shippings = $this->Category->findById($id, array('fields' => 'shipping_cost'));
        $return_arr['shipping_cost'] = $shippings['Category']['shipping_cost'];
        echo json_encode($return_arr);
        $this->autoRender = false;
    }

    function deleteinternationalshippingmethods($id=null) {
        $this->layout = false;

        if ($this->ProductInternationalShipping->delete($id)) {
            $return_arr['message'] = "Yes";
        } else {
            $return_arr['message'] = "No";
        }
        $return_arr['RowId'] = $id;
        echo json_encode($return_arr);
        $this->autoRender = false;
    }

    function deleteshippingmethods($id=null, $id2=null) {
        $this->layout = false;

        if ($this->ProductShipping->delete($id)) {
            $return_arr['message'] = "Yes";
        } else {
            $return_arr['message'] = "No";
        }
        $return_arr['RowId'] = $id;
        echo json_encode($return_arr);
        $this->autoRender = false;
    }

    function deletethumbimage($id=null) {
        $this->layout = false;
        $this->ProductImage->recursive = -1;
        $ProductImage = $this->ProductImage->findById($id);
        //$this->Uploader->delete('img/imagecache/'.$ProductImage['ProductImage']['image']);
        //$this->Uploader->delete('img/thumbs/'.$ProductImage['ProductImage']['image']);
        //$this->Uploader->delete('img/uploads/'.$ProductImage['ProductImage']['image']);
        if ($this->ProductImage->delete($id)) {
            $return_arr['message'] = "Yes";
        } else {
            $return_arr['message'] = "No";
        }
        $return_arr['RowId'] = $id;
        echo json_encode($return_arr);
        $this->autoRender = false;
    }

    function getshippingmethods($id = null) {
        $this->layout = false;
        $this->Shipping->recursive = -1;
        $shippings = $this->Shipping->findAllById($id);
        echo json_encode($shippings[0]['Shipping']);
        $this->autoRender = false;
    }

    function fetchvaluearray($id=null) {
        $this->layout = false;
        $this->loadModel("Sizevalue");
        $this->Sizevalue->recursive = -1;
        $valuearrays = $this->Sizevalue->findAllBySizetitleId($id);
        $html = "";
        foreach ($valuearrays as $valuearray) {
            $html.='<option value="' . $valuearray['Sizevalue']['id'] . '">' . $valuearray['Sizevalue']['size_value'] . '</option>';
        }
        echo $html;
        $this->autoRender = false;
    }

    function delete($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid id for product', true));
            $this->redirect(array('action' => 'index'));
        }

        if ($this->Product->delete($id)) {
            $this->Session->setFlash(__('Product deleted', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Product was not deleted', true));
        $this->redirect(array('action' => 'index'));
    }

    function endselected($id = null) {
        $this->layout = FALSE;
        $this->autoRender = false;
        if (!$id) {
            //$this->Session->setFlash(__('Invalid id for product', true));
            //$this->redirect(array('action'=>'index'));
        }
        $this->data['Product']['unsold_date'] = date('Y-m-d');
        $this->data['Product']['products_status'] = 'Unsold';
        $this->Product->id = $id;
        $this->Product->save($this->data);
    }

    function activeselected($id = null) {
        $this->layout = FALSE;
        $this->Product->recursive = -1;
        $chek = $this->Product->find('first', array('conditions' => array('Product.id' => $id), 'fields' => array('Product.pendingtounsold')));

        if ($chek['Product']['pendingtounsold'] == 'No') {
            $this->Product->id = $id;
            $this->Product->saveField('products_status', 'Active');
        } else {
            $this->Product->id = $id;
            $this->Product->saveField('products_status', 'Pending');
        }
        $this->autoRender = false;
    }

    function unsoldselected($id = null) {
        $this->layout = FALSE;
        $this->data['Product']['pendingtounsold'] = 'Yes';
        $this->data['Product']['unsold_date'] = date('Y-m-d');
        $this->data['Product']['products_status'] = 'Unsold';
        $this->Product->id = $id;
        $this->Product->save($this->data);
        $this->autoRender = false;
    }

    function end($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid id for product', true));
            $this->redirect(array('action' => 'index'));
        }

        if ($id) {
            $this->Product->id = $id;
            $this->Product->saveField('products_status', 'Unsold');
            $this->Session->setFlash(__('Product Ended successfully', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Product was not End', true));
        $this->redirect(array('action' => 'index'));
    }

    function product_disapproved($pid=null) {
        $this->layout = FALSE;
        if (!empty($this->data)) {
            $this->data['Product']['disapproved_date'] = date("Y-m-d H:i:s");
            $this->data['Product']['approved_id'] = $this->Auth->user('id');
            ;
            $this->data['Product']['products_status'] = 'Disapproved';
            $this->Product->save($this->data);
            $this->Product->Behaviors->attach('Containable');
            $this->Product->contain('User.username', 'User.email');
            $products = $this->Product->find('first', array('conditions' => array('Product.id' => $this->data['Product']['id']),
                'fields' => array('Product.products_title', 'Product.user_id', 'Product.id')));
            $this->loadModel('Aprovalnotification');
            $chk = $this->Aprovalnotification->find('first', array('conditions' => array('Aprovalnotification.user_id' => $products['Product']['user_id'])));
            if ($chk['Aprovalnotification']['status'] == 1) {
////////for send email////////
                $this->Email->to = $products['User']['email'];
                //$this->Email->bcc = array('secret@example.com');
                $this->Email->subject = 'About Disapproval of your product--(' . $products['Product']['products_title'] . '),(Item # ' . $this->data['Product']['id'] . ')';
                //$this->Email->replyTo = 'noreply@authenticavenue.com';
                $this->Email->from = $this->Auth->user('username') . '<' . $this->Auth->user('email') . '>';
                $this->Email->template = 'product_disapproved'; // note no '.ctp'
                //Send as 'html', 'text' or 'both' (default is 'text')
                $this->Email->sendAs = 'html'; // because we like to send pretty mail
                //Set view variables as normal
                $this->set('reason', $this->data['Product']['product_comments']);
                $this->set('products', $products);
                $this->Email->send();
            }
            $this->render('disapprovedsuccess');
        } else {
            $this->set('pid', $pid);
        }
    }

    function product_disapproved_selected() {
        $this->layout = FALSE;
        if (!empty($this->data)) {
            $productids = explode(',', $this->data['Product']['id']);
            foreach ($productids as $productids_value) {
                $this->data['Product']['id'] = $productids_value;
                $this->data['Product']['disapproved_date'] = date("Y-m-d H:i:s");
                $this->data['Product']['approved_id'] = $this->Auth->user('id');
                ;
                $this->data['Product']['products_status'] = 'Disapproved';
                //$this->Product->create();
                $this->Product->save($this->data);
                $this->Product->Behaviors->attach('Containable');
                $this->Product->contain('User.username', 'User.email');
                $products = $this->Product->find('first', array('conditions' => array('Product.id' => $productids_value),
                    'fields' => array('Product.products_title', 'Product.user_id', 'Product.id')));
                $this->loadModel('Aprovalnotification');
                $chk = $this->Aprovalnotification->find('first', array('conditions' => array('Aprovalnotification.user_id' => $products['Product']['user_id'])));
                if ($chk['Aprovalnotification']['status'] == 1) {

                    ////////for send email////////
                    $this->Email->to = $products['User']['email'];
                    //$this->Email->bcc = array('secret@example.com');
                    $this->Email->subject = 'About Disapproval of your product--(' . $products['Product']['products_title'] . '),(Item # ' . $productids_value . ')';
                    //$this->Email->replyTo = 'noreply@authenticavenue.com';
                    $this->Email->from = $this->Auth->user('username') . '<' . $this->Auth->user('email') . '>';
                    $this->Email->template = 'product_disapproved'; // note no '.ctp'
                    //Send as 'html', 'text' or 'both' (default is 'text')
                    $this->Email->sendAs = 'html'; // because we like to send pretty mail
                    //Set view variables as normal
                    $this->set('reason', $this->data['Product']['product_comments']);
                    $this->set('products', $products);
                    //Do not pass any args to send()
                    $this->Email->send();
                }
                //////////////////////////////
            }
            $this->render('disapprovedsuccess');
        }
    }

    function product_approved($pid=null) {
        $this->layout = FALSE;
        $this->Product->id = $pid;
        $this->data['Product']['approved_date'] = date("Y-m-d H:i:s");
        $this->data['Product']['approved_id'] = $this->Auth->user('id');
        ;
        $this->data['Product']['products_status'] = 'Approved';
        $this->Product->save($this->data);
        $this->Product->Behaviors->attach('Containable');
        $this->Product->contain('User.username', 'User.email');
        $products = $this->Product->find('first', array('conditions' => array('Product.id' => $pid),
            'fields' => array('Product.products_title', 'Product.user_id', 'Product.id')));

        $this->loadModel('Aprovalnotification');
        $chk = $this->Aprovalnotification->find('first', array('conditions' => array('Aprovalnotification.user_id' => $products['Product']['user_id'])));
        if ($chk['Aprovalnotification']['status'] == 1) {
            ////////for send email////////
            $this->Email->to = $products['User']['email'];
            //$this->Email->bcc = array('secret@example.com');
            $this->Email->subject = 'About approval of your product--(' . $products['Product']['products_title'] . '),(Item # ' . $pid . ')';
            //$this->Email->replyTo = 'noreply@authenticavenue.com';
            $this->Email->from = $this->Auth->user('username') . '<' . $this->Auth->user('email') . '>';
            $this->Email->template = 'product_approved'; // note no '.ctp'
            //Send as 'html', 'text' or 'both' (default is 'text')
            $this->Email->sendAs = 'html'; // because we like to send pretty mail
            //Set view variables as normal
            $this->set('products', $products);
            $this->Email->send();
        }
        $this->autoRender = false;
    }

    function backstage_index() {
        $this->Product->recursive = 0;
        $this->set('products', $this->paginate());
    }

    function backstage_view($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid product', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->set('product', $this->Product->read(null, $id));
    }

    function block() {
        $this->layout = false;
        if (isset($this->data)) {
            $d = base64_encode(serialize($this->data));
            $this->Session->write('blockCountry', $d);
            $return_array['msg'] = "Yes";
            echo json_encode($return_array);
        } else {
            $return_array['msg'] = "No";
            echo json_encode($return_array);
        }
        $this->autoRender = false;
    }

    function blockcountry($id=null) {
        $this->layout = false;
        $this->loadModel('Country');
        $this->loadModel('Continent');
        $this->loadModel('BlockCountryShip');
        $this->Country->recursive = -1;
        $this->BlockCountryShip->recursive = -1;

        if (!empty($id))
            $check = $this->BlockCountryShip->find('all', array('conditions' => array('BlockCountryShip.product_id' => $id, 'BlockCountryShip.seller_id' => $this->Auth->user('id')), 'fields' => array('country_id')));

        $i = 0;
        if (!empty($check)) {
            foreach ($check as $chkv):
                $cid[$i] = $chkv['BlockCountryShip']['country_id'];
                $i++;
            endforeach;
        }else {
            $cid = array();
        }

        if (!empty($cid)) {
            $this->set('cid', $cid);
            $this->set('cna', $this->BlockCountryShip->find('count', array('conditions' => array('BlockCountryShip.product_id' => $id, 'BlockCountryShip.seller_id' => $this->Auth->user('id'), 'BlockCountryShip.continent_id' => 1))));
            $this->set('na', $this->Country->find('all', array('conditions' => array('Country.continent_id' => 1))));
            $this->set('csa', $this->BlockCountryShip->find('count', array('conditions' => array('BlockCountryShip.product_id' => $id, 'BlockCountryShip.seller_id' => $this->Auth->user('id'), 'BlockCountryShip.continent_id' => 2))));
            $this->set('sa', $this->Country->find('all', array('conditions' => array('Country.continent_id' => 2))));
            $this->set('cep', $this->BlockCountryShip->find('count', array('conditions' => array('BlockCountryShip.product_id' => $id, 'BlockCountryShip.seller_id' => $this->Auth->user('id'), 'BlockCountryShip.continent_id' => 3))));
            $this->set('ep', $this->Country->find('all', array('conditions' => array('Country.continent_id' => 3))));
            $this->set('cas', $this->BlockCountryShip->find('count', array('conditions' => array('BlockCountryShip.product_id' => $id, 'BlockCountryShip.seller_id' => $this->Auth->user('id'), 'BlockCountryShip.continent_id' => 4))));
            $this->set('as', $this->Country->find('all', array('conditions' => array('Country.continent_id' => 4))));
            $this->set('coc', $this->BlockCountryShip->find('count', array('conditions' => array('BlockCountryShip.product_id' => $id, 'BlockCountryShip.seller_id' => $this->Auth->user('id'), 'BlockCountryShip.continent_id' => 5))));
            $this->set('oc', $this->Country->find('all', array('conditions' => array('Country.continent_id' => 5))));
            $this->set('caf', $this->BlockCountryShip->find('count', array('conditions' => array('BlockCountryShip.product_id' => $id, 'BlockCountryShip.seller_id' => $this->Auth->user('id'), 'BlockCountryShip.continent_id' => 6))));
            $this->set('af', $this->Country->find('all', array('conditions' => array('Country.continent_id' => 6))));
        } else {
            $this->set('cid', $cid);
            $this->set('cna', 0);
            $this->set('na', $this->Country->find('all', array('conditions' => array('Country.continent_id' => 1))));
            $this->set('csa', 0);
            $this->set('sa', $this->Country->find('all', array('conditions' => array('Country.continent_id' => 2))));
            $this->set('cep', 0);
            $this->set('ep', $this->Country->find('all', array('conditions' => array('Country.continent_id' => 3))));
            $this->set('cas', 0);
            $this->set('as', $this->Country->find('all', array('conditions' => array('Country.continent_id' => 4))));
            $this->set('coc', 0);
            $this->set('oc', $this->Country->find('all', array('conditions' => array('Country.continent_id' => 5))));
            $this->set('caf', 0);
            $this->set('af', $this->Country->find('all', array('conditions' => array('Country.continent_id' => 6))));
        }
    }

    function backstage_add() {

        if (!empty($this->data)) {
            $this->Product->create();
            if ($this->Product->save($this->data)) {
                $this->Session->setFlash(__('The product has been saved', true));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The product could not be saved. Please, try again.', true));
            }
        }
        $users = $this->Product->User->find('list');
        $categories = $this->Product->Category->find('list');
        $this->set(compact('users', 'categories'));
    }

    function backstage_edit($id = null) {
        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Invalid product', true));
            $this->redirect(array('action' => 'index'));
        }
        if (!empty($this->data)) {
            if ($this->Product->save($this->data)) {
                $this->Session->setFlash(__('The product has been saved', true));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The product could not be saved. Please, try again.', true));
            }
        }
        if (empty($this->data)) {
            $this->data = $this->Product->read(null, $id);
        }
        $users = $this->Product->User->find('list');
        $categories = $this->Product->Category->find('list');
        $this->set(compact('users', 'categories'));
    }

    function backstage_delete($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid id for product', true));
            $this->redirect(array('action' => 'index'));
        }
        if ($this->Product->delete($id)) {
            $this->Session->setFlash(__('Product deleted', true));
            $this->redirect(array('action' => 'index'));
        }

        $this->Session->setFlash(__('Product was not deleted', true));
        $this->redirect(array('action' => 'index'));
    }

    function success() {
        $this->layout = false;
    }

    function details($id=NULL) {
        $this->layout = 'details';
        //getting products
        $this->Product->recursive = 2;
        $this->Product->Behaviors->attach('Containable');
        $this->Product->contain('User.Group', 'User.City', 'User.State', 'User.Country', 'Category', 'Brand', 'ProductImage', 'HandleTime');
        $products = $this->Product->find('first', array('conditions' => array('OR' => array(array('Product.products_status' => 'Active'), array('Product.products_status' => 'Approved')), 'Product.products_expiredDate >=' => date("Y-m-d H:i:s"), 'Product.id' => $id)));
        //pr($products);
        $this->loadModel('BlockCountry');
        $blockCountries = $this->BlockCountry->find('all', array('conditions' => array('BlockCountry.seller_id' => $products['Product']['user_id']), 'order' => array('Country.name', 'Country.name ASC')));
        if (count($blockCountries) != 0) {
            $this->set('blockCountries', $blockCountries);
            //check if current user from block countries
            foreach ($blockCountries as $blockCountry) {
                if (array_search($this->Auth->user('country_id'), $blockCountry['Country']) !== FALSE) {
                    $this->render('block_countries');
                    return;
                }
            }
        }
        //calulate commition and negotiations
        $buyerId = $this->Auth->User('id') == NULL ? 0 : $this->Auth->User('id');
        $this->set('commition', $this->Product->commition($products, $buyerId));
        $this->Product->query("update authentic_products set `products_views`=`products_views`+1 where `id`=$id;");
        $this->Categorybrand->Behaviors->attach('Containable');
        $this->Categorybrand->contain('Brand.brand_description');
        $categoryBrandCondition = $this->Categorybrand->find('first', array('conditions' => array('Brand.id' => $products['Product']['global_conditions'], 'Categorybrand.brand_type' => 'condition', 'Categorybrand.category_id' => $products['Product']['category_id'])));
        $this->set('conditions', $categoryBrandCondition);
        $this->set('styles', $this->Categorybrand->find('first', array('conditions' => array('Brand.id' => $products['Product']['global_styles'], 'Categorybrand.brand_type' => 'style'), 'Categorybrand.category_id' => $products['Product']['category_id'])));
        $this->set('brands', $this->Categorybrand->find('first', array('conditions' => array('Brand.id' => $products['Product']['global_brands'], 'Categorybrand.brand_type' => 'brand'), 'Categorybrand.category_id' => $products['Product']['category_id'])));
        $this->set('productFields', $this->Field->find('all', array('conditions' => array('Field.category_id' => $products['Product']['category_id']))));

        $this->ProductSize->Behaviors->attach('Containable');
        $this->ProductSize->contain('Sizetitle', 'Sizevalue', 'Sizelabel');
        $options['order'] = array('ProductSize.sizelabel_id DESC');
        $options['conditions'] = array('ProductSize.product_id' => $products['Product']['id'], 'ProductSize.category_id' => $products['Product']['category_id']);
        $options['fields'] = array('ProductSize.*', 'Sizevalue.size_value', 'Sizetitle.size_title', 'Sizelabel.size_label');
        $this->data['selected_size'] = $this->ProductSize->find('all', $options);

        $this->set('domesticShipping', $this->ProductShipping->find('all', array('conditions' => array('ProductShipping.product_id' => $products['Product']['id']))));
        $this->ProductInternationalShipping->unbindModel(array('belongsTo' => array('Continent')));
        $productinternationalshippings = $this->ProductInternationalShipping->find('all', array('conditions' => array('ProductInternationalShipping.product_id' => $id)));
        $i = 0;
        $this->loadModel("Continent");
        $this->Continent->recursive = -1;
        foreach ($productinternationalshippings as $productinternationalshipping):
            if ($productinternationalshipping['ProductInternationalShipping']['continent_id'] != "worldwide") {
                $conID = explode(",", $productinternationalshipping['ProductInternationalShipping']['continent_id']);
                $flag = 1;
                $continent = "";
                foreach ($conID as $continentID) {
                    $continent_name = $this->Continent->find("first", array("conditions" => array("id" => $continentID), "fields" => array("name")));
                    if ($flag == 1) {
                        $continent.=$continent_name['Continent']['name'];
                        $flag = 0;
                    }
                    else
                        $continent.=", " . $continent_name['Continent']['name'];
                }
                $productinternationalshippings[$i]['ProductInternationalShipping']['continent_id'] = $continent;
            }
            else
                $productinternationalshippings[$i]['ProductInternationalShipping']['continent_id'] = $productinternationalshipping['ProductInternationalShipping']['continent_id'];
            $i++;
        endforeach;
        $this->set('internationalShipping', $productinternationalshippings);
        $this->set('products', $products);
        $this->set('item', $this->Category->categoryArray());
        $this->loadModel('Rating');
        $this->set('productRating', $this->Rating->checkRating($products['User']['id'], $products['Product']['id']));
        $this->loadModel('Returnpolicy');
        if ($products['Product']['products_returnPolicyType'] == "Yes") {
            $returnpolicies = $this->Returnpolicy->findBySellerId($products['Product']['user_id']);
            $returnpolicy = $returnpolicies['Returnpolicy']['policy'];
        } else {
            $returnpolicy = $products['Product']['products_returnPolicy'];
        }
        $this->set('returnpolicy', $returnpolicy);
        if ($this->Auth->User('id') != NULL) {
            $this->loadModel('Order');
            $countvalue = $this->Order->find('count', array('conditions' => array('Order.user_id' => $this->Auth->User('id'), 'Order.product_id' => $id)));
            $this->set('alreadybuy', $countvalue);
            if ($countvalue > 0) {
                $buyingdate = $this->Order->find('first', array('conditions' => array('Order.user_id' => $this->Auth->User('id'), 'Order.product_id' => $id), 'recursive' => -1, 'fields' => array('Order.id', 'Order.add_date')));
                $this->set('buyingdate', $buyingdate);
            }
        }
    }

    function ratingSave() {
        $this->layout = FALSE;
        $this->autoRender = FALSE;
        $this->loadModel('Rating');
        if ($this->Rating->save($this->data)) {
            echo 'Feedback has been submitted successfully.';
        } else {
            echo 'Feedback does not save. Please try again.';
        }
    }

    function feedback_chk_byuser($pid, $userid) {
        $this->layout = FALSE;
        $this->autoRender = FALSE;
        $this->loadModel('Rating');
        return $this->Rating->find('count', array('conditions' => array('Rating.buyer_id' => $userid, 'Rating.product_id' => $pid)));
    }

    function addnote($pid=null) {
        $this->layout = false;
        $this->data['Note']['product_id'] = $pid;
        $this->data['Note']['user_id'] = $this->Auth->user('id');
        $this->Note->save($this->data);
        $this->set('pid', $pid);
    }

    function updatenote($id=null) {
        $this->layout = false;
        $this->autoRender = false;
        $this->Note->id = $id;
        $this->Note->save($this->data);
        echo 'success';
        //$this->set('pid', $pid);
    }

    function addnote_pending($pid=null, $sid=null) {
        $this->layout = false;
        if (!empty($this->data)) {
            if (!empty($this->data['Note']['id'])) {
                $this->Note->id = $this->data['Note']['id'];
                $this->Note->save($this->data);
            } else {
                $this->data['Note']['user_id'] = $this->Auth->user('id');
                $this->Note->save($this->data);
            }
            $this->Render('notesuccess');
        } else {
            $this->set('pid', $pid);
            $this->set('sid', $sid);
        }
    }

    function addnote_selected($pid=null, $sid=null) {
        $this->layout = false;
        if (!empty($this->data)) {
            if (!empty($this->data['Note']['product_ids'])) {
                $productids = explode(',', $this->data['Note']['product_ids']);
                foreach ($productids as $productids_value) {
                    $this->Note->recursive = -1;
                    $ise = $this->Note->find('first', array('fields' => array('Note.id'), 'conditions' => array('Note.user_id' => $this->Auth->user('id'), 'Note.product_id' => $productids_value)));
                    if (!empty($ise)) {
                        $this->data['Note']['id'] = $ise['Note']['id'];
                        $this->Note->create();
                        $this->Note->save($this->data);
                    } else {
                        $this->Note->create();
                        $this->data['Note']['product_id'] = $productids_value;
                        $this->data['Note']['user_id'] = $this->Auth->user('id');
                        $this->Note->save($this->data);
                    }
                }
                $this->Render('notesuccess');
            } else {
                $this->set('productempty', 'Please select at least one product.');
            }
        }
    }

    function addnote_reportitem($pid=null, $sid=null) {
        $this->layout = false;
        $this->loadModel('Reportnote');
        if (!empty($this->data)) {
            if (!empty($this->data['Reportnote']['product_ids'])) {
                $productids = explode(',', $this->data['Reportnote']['product_ids']);
                foreach ($productids as $productids_value) {
                    $this->Reportnote->recursive = -1;
                    $ise = $this->Reportnote->find('first', array('fields' => array('Reportnote.id'), 'conditions' => array('Reportnote.user_id' => $this->Auth->user('id'), 'Reportnote.product_id' => $productids_value)));
                    if (!empty($ise)) {
                        $this->data['Reportnote']['id'] = $ise['Reportnote']['id'];
                        $this->Reportnote->create();
                        $this->Reportnote->save($this->data);
                    } else {
                        $this->Reportnote->create();
                        $this->data['Reportnote']['product_id'] = $productids_value;
                        $this->data['Reportnote']['user_id'] = $this->Auth->user('id');
                        $this->Reportnote->save($this->data);
                    }
                }
                $this->Render('notesuccess');
            } else {
                $this->set('productempty', 'Please select at least one product.');
            }
        }
    }

    function addnote_reporteditem($pid=null) {
        $this->layout = false;
        $this->loadModel('Reportnote');
        if (!empty($this->data)) {
            $this->Reportnote->recursive = -1;
            $ise = $this->Reportnote->find('first', array('fields' => array('Reportnote.id'), 'conditions' => array('Reportnote.user_id' => $this->Auth->user('id'), 'Reportnote.product_id' => $this->data['Reportnote']['product_id'])));
            if (!empty($ise)) {
                $this->data['Reportnote']['id'] = $ise['Reportnote']['id'];
                $this->Reportnote->create();
                $this->Reportnote->save($this->data);
            } else {
                $this->Reportnote->create();
                $this->data['Reportnote']['user_id'] = $this->Auth->user('id');
                $this->Reportnote->save($this->data);
            }
            $this->Render('notesuccess');
        }
        $this->set('pid', $pid);
    }

    function addsoldnote_selected($pid=null, $sid=null) {
        $this->layout = false;
        $this->loadModel('Soldnote');
        if (!empty($this->data)) {
            if (!empty($this->data['Soldnote']['product_ids'])) {
                $productids = explode(',', $this->data['Soldnote']['product_ids']);
                foreach ($productids as $productids_value) {
                    $this->Soldnote->recursive = -1;
                    $ise = $this->Soldnote->find('first', array('fields' => array('Soldnote.id'), 'conditions' => array('Soldnote.user_id' => $this->Auth->user('id'), 'Soldnote.product_id' => $productids_value)));
                    if (!empty($ise)) {
                        $this->data['Soldnote']['id'] = $ise['Soldnote']['id'];
                        $this->Soldnote->create();
                        $this->Soldnote->save($this->data);
                    } else {
                        $this->Soldnote->create();
                        $this->data['Soldnote']['product_id'] = $productids_value;
                        $this->data['Soldnote']['user_id'] = $this->Auth->user('id');
                        $this->Soldnote->save($this->data);
                    }
                }
                $this->Render('notesuccess');
            } else {
                $this->set('productempty', 'Please select at least one product.');
            }
        }
    }

    function getnote($pid=null, $uid=null, $flag=null) {
        $this->layout = false;
        $this->autoRender = false;
        if ($flag == "1") {
            $this->Note->Behaviors->attach('Containable');
            $this->Note->contain('User.username');
            return $this->Note->find('all', array('conditions' => array('Note.product_id' => $pid, 'Note.user_id !=' => $uid)));
        } elseif ($flag == "2") {
            $this->Note->Behaviors->attach('Containable');
            $this->Note->contain('User.username');
            return $this->Note->find('all', array('conditions' => array('Note.product_id' => $pid, 'Note.user_id' => $uid)));
        } else {
            $this->Note->recursive = -1;
            return $this->Note->findAllByProductId($pid);
        }
    }

    function getnotereport($pid=null, $uid=null) {
        $this->layout = false;
        $this->autoRender = false;
        $this->loadModel('Reportnote');
        $this->Reportnote->Behaviors->attach('Containable');
        $this->Reportnote->contain('User.username');
        return $this->Reportnote->find('all', array('conditions' => array('Reportnote.product_id' => $pid, 'Reportnote.user_id !=' => $uid)));
    }

    function getsoldnote($pid=null, $uid=null, $flag=null) {
        $this->layout = false;
        $this->autoRender = false;
        $this->loadModel('Soldnote');
        $this->Soldnote->Behaviors->attach('Containable');
        $this->Soldnote->contain('User.username');
        return $this->Soldnote->find('all', array('conditions' => array('Soldnote.product_id' => $pid, 'Soldnote.user_id' => $uid)));
    }

    function ask_a_question($id) {
        $this->layout = false;
        $this->Product->recursive = 2;
        $this->Product->Behaviors->attach('Containable');
        $this->Product->contain('User.Group');
        $this->set('qData', $this->Product->find('first', array('conditions' => array('Product.id' => $id))));
    }

    function sendMessege() {
        $this->layout = false;
        $this->autoRender = false;
        $this->loadModel('Message');
        $this->loadModel('MessageTrack');
        if (isset($this->data)) {
            $this->Message->save($this->data['Message']);
            $this->data['MessageTrack']['message_id'] = $this->Message->getLastInsertId();
            $this->MessageTrack->save($this->data['MessageTrack']);
            $this->data['MessageTrack']['id'] = NULL;
            $this->data['MessageTrack']['msg_type'] = 0;
            $this->MessageTrack->save($this->data['MessageTrack']);
        }
    }

    function advance_search($id=null, $id2=null) {
        $this->layout = 'innerhome';
        $this->set('item', $this->Category->categoryArray());
        // $this->set('homePageContent', $this->Product->homePageProducts($this->Category->randomCategory()));
        $categories = $this->Product->Category->find('list');
        $this->set(compact('categories'));
        if ($id2 == "thumb")
            $this->set('thumb', "thumb");
        if (!empty($id))
            $_POST['serchkey'] = $id;
        if (!empty($_POST)) {            
            $searchkey = explode(" ", $_POST['keywords']);
            $this->set('searchkey', $_POST['keywords']);
            $this->Product->Behaviors->attach('Containable');
            $this->Product->contain('User.username');
            if ($_POST['sortby'] == 1) {
                $fild = 'Product.products_expiredDate';
                $ord = 'ASC';
            } elseif ($_POST['sortby'] == 2) {
                $fild = 'Product.products_createDate';
                $ord = 'DESC';
            } elseif ($_POST['sortby'] == 3) {
                $fild = 'Product.products_price';
                $ord = 'DESC';
            } else {
                $fild = 'Product.products_price';
                $ord = 'ASC';
            }
            $flds = array('Product.id', 'Product.user_id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.products_views', 'Product.products_price', 'Product.products_status', 'DATEDIFF(products_expiredDate,now()) AS totaldays');
            for ($i = 0; $i < count($searchkey); $i++) {
                $p_title[$i] = "Product.products_title like '%" . $searchkey[$i] . "%'";
                $p_des[$i] = "Product.products_description like '%" . $searchkey[$i] . "%'";                
            }
            if (isset($_POST['com_list']) AND isset($_POST['tle_des'])) {
                if (!empty($this->data['Product']['categories'])) {
                    $prms = array(
                        'conditions' => array(
                            'Product.category_id' => $this->data['Product']['categories'],
                            'OR' => array(
                                    'Product.products_status !=' => 'Pending',
                                    'Product.products_status !=' => 'Disapproved'
                                ),
                            'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                            'AND' => array(
                                    'OR'=>array(
                                            array(
                                            'OR' => $p_title
                                            ),
                                    array(
                                            'OR' => $p_des
                                            )
                                    )
                            )
                            ),
                        'order' => array($fild => $ord),
                        'fields' => $flds,
                        'contain' => array(
                            'User.username',
                            'Approver.username'
                        )
                    );
                } else {
                    $prms = array(
                        'conditions' => array(
                            'OR' => array('Product.products_status !=' => 'Pending',
                                'Product.products_status !=' => 'Disapproved'),
                            'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                            'AND' => array(
                                    'OR'=>array(
                                            array(
                                            'OR' => $p_title
                                            ),
                                    array(
                                            'OR' => $p_des
                                            )
                                    )
                            )                            
                            ),
                        'order' => array($fild => $ord),
                        'fields' => $flds,
                        'contain' => array(
                            'User.username',
                            'Approver.username'
                        )
                    );
                }
            } elseif (isset($_POST['com_list'])) {
                if (is_numeric($_POST['keywords'])) {
                    if (!empty($this->data['Product']['categories'])) {
                        $prms = array(
                            'conditions' => array(
                                'Product.category_id' => $this->data['Product']['categories'],
                                'OR' => array('Product.products_status !=' => 'Pending',
                                    'Product.products_status !=' => 'Disapproved'),
                                'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                                'Product.id' => $_POST['keywords']
                            ),
                            'order' => array($fild => $ord),
                            'fields' => $flds,
                            'contain' => array(
                                'User.username',
                                'Approver.username'
                            )
                        );
                    } else {
                        $prms = array(
                            'conditions' => array(
                                'Product.id' => $_POST['keywords'],
                                'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                                'OR' => array('Product.products_status !=' => 'Pending',
                                    'Product.products_status !=' => 'Disapproved')),
                            'order' => array($fild => $ord),
                            'fields' => $flds,
                            'contain' => array(
                                'User.username',
                                'Approver.username'
                            )
                        );
                    }
                } else {
                    if (!empty($this->data['Product']['categories'])) {
                        $prms = array(
                            'conditions' => array(
                                'OR' => array('Product.products_status !=' => 'Pending',
                                    'Product.products_status !=' => 'Disapproved'),
                                'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                                'Product.products_title like' => '%' . $_POST['keywords'] . '%',
                                'Product.category_id' => $this->data['Product']['categories']),
                            'order' => array($fild => $ord),
                            'fields' => $flds,
                            'contain' => array(
                                'User.username',
                                'Approver.username'
                            )
                        );
                    } else {
                        $prms = array(
                            'conditions' => array(
                                'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                                'OR' => array('Product.products_status !=' => 'Pending',
                                    'Product.products_status !=' => 'Disapproved'),
                                'Product.products_title like' => '%' . $_POST['keywords'] . '%'),
                            'order' => array($fild => $ord),
                            'fields' => $flds,
                            'contain' => array(
                                'User.username',
                                'Approver.username'
                            )
                        );
                       
                    }
                }
            } elseif (isset($_POST['tle_des'])) {
                if (!empty($this->data['Product']['categories'])) {
                    $prms = array(
                        'conditions' => array(
                            'Product.category_id' => $this->data['Product']['categories'],
                            'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                            'OR' => array('Product.products_status !=' => 'Pending',
                                'Product.products_status !=' => 'Disapproved'),
                            'AND' => array(
                                    'OR'=>array(
                                            array(
                                            'OR' => $p_title
                                            ),
                                    array(
                                            'OR' => $p_des
                                            )
                                    )
                            )                            
                            ),
                        'order' => array($fild => $ord),
                        'fields' => $flds,
                        'contain' => array(
                            'User.username',
                            'Approver.username'
                        )
                    );
                } else {
                    $prms = array(
                        'conditions' => array('OR' => array(
                                'Product.products_status !=' => 'Pending',
                                'Product.products_status !=' => 'Disapproved'),
                            'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),                            
                            'AND' => array(
                                        'OR'=>array(
                                                array(
                                                'OR' => $p_title
                                                ),
                                        array(
                                                'OR' => $p_des
                                                )
                                        )
                                )
                            ),
                        'order' => array($fild => $ord),
                        'fields' => $flds,
                        'contain' => array(
                            'User.username',
                            'Approver.username'
                        )
                    );
                }
            } else {
                if (is_numeric($_POST['keywords'])) {
                    if (!empty($this->data['Product']['categories'])) {
                        $prms = array(
                            'conditions' => array(
                                'Product.id' => $_POST['keywords'],
                                'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                                'Product.category_id' => $this->data['Product']['categories'],
                                'OR' => array('Product.products_status !=' => 'Pending',
                                    'Product.products_status !=' => 'Disapproved'
                            )),
                            'order' => array($fild => $ord),
                            'fields' => $flds,
                            'contain' => array(
                                'User.username',
                                'Approver.username'
                            )
                        );
                    } else {
                        $prms = array(
                            'conditions' => array(
                                'Product.id' => $_POST['keywords'],
                                'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                                'OR' => array('Product.products_status !=' => 'Pending',
                                    'Product.products_status !=' => 'Disapproved'
                            )),
                            'order' => array($fild => $ord),
                            'fields' => $flds,
                            'contain' => array(
                                'User.username',
                                'Approver.username'
                            )
                        );
                    }
                } else {
                    if (!empty($this->data['Product']['categories'])) {
                        $prms = array(
                            'conditions' => array(
                                'OR' => array('Product.products_status !=' => 'Pending',
                                    'Product.products_status !=' => 'Disapproved'),
                                'Product.products_title like' => '%' . $_POST['keywords'] . '%',
                                'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                                'Product.category_id' => $this->data['Product']['categories']),
                            'order' => array($fild => $ord),
                            'fields' => $flds,
                            'contain' => array(
                                'User.username',
                                'Approver.username'
                            )
                        );
                    } else {
                        $prms = array(
                            'conditions' => array(
                                'OR' => array('Product.products_status !=' => 'Pending',
                                    'Product.products_status !=' => 'Disapproved'),
                                'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                                'Product.products_title like' => '%' . $_POST['keywords'] . '%'),
                            'order' => array($fild => $ord),
                            'fields' => $flds,
                            'contain' => array(
                                'User.username',
                                'Approver.username'
                            )
                        );
                    }
                }
            }
            
            $products=$this->Product->find('all', $prms);           
            $product_list = Set::extract('/Product/id', $products);            
            $this->set('products', $products);
            $this->set('viewresult', $_POST['view_result']);
            
            //Fetching related category list
            $flds_cat = array('Product.category_id', 'count(Product.category_id) as total');
            $prms_cat = array(
                'conditions' => array('Product.id' => $product_list),                        
                'order' => 'total desc',
                'group' => 'Product.category_id',
                'fields' => $flds_cat
            );
            $this->Product->contain('Category.category_name');
            $cat_list = $this->Product->find('all', $prms_cat);
              
             //Fetching brand list
            $flds_brands = array('Product.global_brands', 'count(Product.global_brands) as totalproduct');
            $prms_brands = array(
                'conditions' => array('Product.id' => $product_list),
                'order' => 'totalproduct desc',
                'group' => 'Product.global_brands',
                'fields' => $flds_brands
            );
            $this->Product->contain('Brand.brand_description');
            $brands_list = $this->Product->find('all', $prms_brands);

            //Fetching condition list
            $flds_conditions = array('Product.global_conditions', 'count(Product.global_conditions) as totalproduct');
            $prms_conditions = array(
                'conditions' => array('Product.id' => $product_list),
                'order' => 'totalproduct desc',
                'group' => 'Product.global_conditions',
                'fields' => $flds_conditions
            );
            $this->Product->contain('ProductCondition.brand_description');
            $conditions_list = $this->Product->find('all', $prms_conditions);

            //Fetching style list
            $flds_styles = array('Product.global_styles', 'count(Product.global_styles) as totalproduct');
            $prms_styles = array(
                'conditions' => array('Product.id' => $product_list),
                'order' => 'totalproduct desc',
                'group' => 'Product.global_styles',
                'fields' => $flds_styles
            );
            $this->Product->contain('ProductStyle.brand_description');
            $styles_list = $this->Product->find('all', $prms_styles);

            //Fetching size list
            $flds_p = array('Product.id');
            $prms_p = array(
                'conditions' => array('Product.id' => $product_list),
                'order' => array('Product.id' => 'DESC'),
                'group' => 'Product.id',
                'fields' => $flds_p,
            );
            $p_list = $this->Product->find('list', $prms_p);

            $flds_sizes = array('Sizevalue.size_value');
            $prms_sizes = array(
                'conditions' => array(
                    'ProductSize.product_id' => $product_list,
                ),
                'fields' => $flds_sizes,
                'group' => 'Sizevalue.size_value',
                'order' => 'Sizevalue.id asc'
            );
            $this->ProductSize->Behaviors->attach('Containable');
            $this->ProductSize->contain('Sizevalue');
            $sizes_list = $this->ProductSize->find('all', $prms_sizes);

            //Fetching Color list
            $color = $this->Field->find('all', array('fields' => array('Field.id'), 'conditions' => array('OR' => array(array('Field.field_name LIKE' => '%Color%'), array('Field.field_name LIKE' => '%Colour%'))), 'order' => 'Field.id  asc', 'recursive' => '-1'));
            $results = Set::extract('/Field/id', $color);
            $colors_list = $this->ProductAdditionalFieldValue->find('all', array('fields' => array('ProductAdditionalFieldValue.values', 'count(ProductAdditionalFieldValue.values) as totalproduct'), 'conditions' => array('ProductAdditionalFieldValue.values !=' => '', 'ProductAdditionalFieldValue.product_id' => $product_list, 'ProductAdditionalFieldValue.field_id' => $results), 'order' => 'totalproduct desc', 'group' => 'ProductAdditionalFieldValue.values', 'recursive' => '-1'));
            // pr($colors_list);

            $this->set('query', '');
            $this->set('search', 1);
            $this->set('item', $cat_list);
            $this->set('leftmenucolor', $colors_list);
            $this->set('leftmenustyle', $styles_list);
            $this->set('leftmenucondition', $conditions_list);
            $this->set('leftmenubrand', $brands_list);
            $this->set('leftmenusize', $sizes_list);

            $this->render('search_result1');
        }else  $this->set('searchkey', "");

        ///////////left-menu//////////////
         $this->set('query', '');
         
        $this->set('leftmenucolor', $this->Field->color_menu());
        $this->set('leftmenustyle', $this->Product->brand_menu('global_styles'));
        $this->set('leftmenucondition', $this->Product->brand_menu('global_conditions'));
        $this->set('leftmenubrand', $this->Product->brand_menu('global_brands'));
        $this->set('leftmenusize', $this->ProductSize->size_menu());
    }

    function search_result($id=null, $id2=null) {
        $this->layout = 'innerhome';
        $this->set('item', $this->Category->categoryArray());
        // $this->set('homePageContent', $this->Product->homePageProducts($this->Category->randomCategory()));
        $categories = $this->Product->Category->find('list');
        $this->set(compact('categories'));
        if ($id2 == "thumb")
            $this->set('thumb', "thumb");
        if (!empty($id))
            $_POST['serchkey'] = $id;
        if (!empty($_POST)) {
            $this->set('searchkey', $_POST['serchkey']);
            $searchkey = explode(" ", $_POST['serchkey']);
            $this->Product->Behaviors->attach('Containable');
            $this->Product->contain('User.username');
            $flds = array('Product.id', 'Product.user_id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.products_views', 'Product.products_price', 'Product.products_status', 'DATEDIFF(products_expiredDate,now()) AS totaldays');
            if (is_numeric($_POST['serchkey'])) {
                if (!empty($_POST['cat_id'])) {

                    $prms = array(
                        'conditions' => array(
                            'Product.category_id' => $_POST['cat_id'],
                            'OR' => array('Product.products_status !=' => 'Pending',
                                'Product.products_status !=' => 'Disapproved'),
                            'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                            'Product.id' => $_POST['serchkey']),
                        'order' => array('Product.id' => 'DESC'),
                        'fields' => $flds,
                        'contain' => array(
                            'User.username',
                            'Approver.username'
                        )
                    );
                } else {

                    $prms = array(
                        'conditions' => array(
                            'OR' => array('Product.products_status !=' => 'Pending',
                                'Product.products_status !=' => 'Disapproved'),
                            'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                            'Product.id' => $_POST['serchkey']),
                        'order' => array('Product.id' => 'DESC'),
                        'fields' => $flds,
                        'contain' => array(
                            'User.username',
                            'Approver.username'
                        )
                    );
                }
            } else {
                if (!empty($_POST['cat_id'])) {
                    for ($i = 0; $i < count($searchkey); $i++) {
                        $p_title[$i] = "Product.products_title like '%" . $searchkey[$i] . "%'";
                        $p_des[$i] = "Product.products_description like '%" . $searchkey[$i] . "%'";                       
                    }
                    
                    $prms = array(
                        'conditions' => array(
                            'OR' => array('Product.products_status !=' => 'Pending', 'Product.products_status !=' => 'Disapproved'),
                            'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                            'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                            ),
                            'Product.category_id' => $_POST['cat_id']),
                        'order' => array('Product.id' => 'DESC'),
                        'fields' => $flds,
                        'contain' => array(
                            'User.username',
                            'Approver.username'
                        )
                    );
                } else {
                    for ($i = 0; $i < count($searchkey); $i++) {
                         $p_title[$i] = "Product.products_title like '%" . $searchkey[$i] . "%'";
                         $p_des[$i] = "Product.products_description like '%" . $searchkey[$i] . "%'";                            
                    }
                    //Product list    
                    $prms = array(
                        'conditions' => array(
                            'OR' => array(
                                array('Product.products_status !=' => 'Pending'),
                                array('Product.products_status !=' => 'Disapproved')
                            ),
                            'AND' => array(
                                'OR'=>array(
                                    array(
                                        'OR' => $p_title
                                    ),
                                    array(
                                        'OR' => $p_des
                                    )
                                )
                            ),
                            'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                        ),
                        'order' => array('Product.id' => 'DESC'),
                        'group' => 'Product.id',
                        'fields' => $flds,
                        'contain' => array(
                            'User.username',
                            'Approver.username'
                        )
                    );
                    //Fetching related category list
                    $flds_cat = array('Product.category_id', 'count(Product.category_id) as total');

                    $prms_cat = array(
                        'conditions' => array(
                            'OR' => array(
                                array('Product.products_status !=' => 'Pending'),
                                array('Product.products_status !=' => 'Disapproved')
                            ),
                            'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                            ),
                            'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                        ),
                        'order' => 'total desc',
                        'group' => 'Product.category_id',
                        'fields' => $flds_cat
                    );
                    $this->Product->contain('Category.category_name');
                    $cat_list = $this->Product->find('all', $prms_cat);

                    //Fetching brand list
                    $flds_brands = array('Product.global_brands', 'count(Product.global_brands) as totalproduct');

                    $prms_brands = array(
                        'conditions' => array(
                            'OR' => array(
                                array('Product.products_status !=' => 'Pending'),
                                array('Product.products_status !=' => 'Disapproved')
                            ),
                            'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                            ),
                            'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                        ),
                        'order' => 'totalproduct desc',
                        'group' => 'Product.global_brands',
                        'fields' => $flds_brands
                    );
                    $this->Product->contain('Brand.brand_description');
                    $brands_list = $this->Product->find('all', $prms_brands);

                    //Fetching condition list
                    $flds_conditions = array('Product.global_conditions', 'count(Product.global_conditions) as totalproduct');

                    $prms_conditions = array(
                        'conditions' => array(
                            'OR' => array(
                                array('Product.products_status !=' => 'Pending'),
                                array('Product.products_status !=' => 'Disapproved')
                            ),
                            'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                            ),
                            'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                        ),
                        'order' => 'totalproduct desc',
                        'group' => 'Product.global_conditions',
                        'fields' => $flds_conditions
                    );
                    $this->Product->contain('ProductCondition.brand_description');
                    $conditions_list = $this->Product->find('all', $prms_conditions);

                    //Fetching style list
                    $flds_styles = array('Product.global_styles', 'count(Product.global_styles) as totalproduct');

                    $prms_styles = array(
                        'conditions' => array(
                            'OR' => array(
                                array('Product.products_status !=' => 'Pending'),
                                array('Product.products_status !=' => 'Disapproved')
                            ),
                            'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                            ),
                            'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                        ),
                        'order' => 'totalproduct desc',
                        'group' => 'Product.global_styles',
                        'fields' => $flds_styles
                    );
                    $this->Product->contain('ProductStyle.brand_description');
                    $styles_list = $this->Product->find('all', $prms_styles);

                    //Fetching size list
                    $flds_p = array('Product.id');
                    $prms_p = array(
                        'conditions' => array(
                            'OR' => array(
                                array('Product.products_status !=' => 'Pending'),
                                array('Product.products_status !=' => 'Disapproved')
                            ),
                            'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                            ),
                            'Product.products_expiredDate >=' => date('Y-m-d H:i:s')
                        ),
                        'order' => array('Product.id' => 'DESC'),
                        'group' => 'Product.id',
                        'fields' => $flds_p,
                    );
                    $p_list = $this->Product->find('list', $prms_p);

                    $flds_sizes = array('Sizevalue.size_value');

                    $prms_sizes = array(
                        'conditions' => array(
                            'ProductSize.product_id' => $p_list,
                        ),
                        'fields' => $flds_sizes,
                        'group' => 'Sizevalue.size_value',
                        'order' => 'Sizevalue.id asc'
                    );
                    $this->ProductSize->Behaviors->attach('Containable');
                    $this->ProductSize->contain('Sizevalue');
                    $sizes_list = $this->ProductSize->find('all', $prms_sizes);

                    //Fetching Color list
                    $color = $this->Field->find('all', array('fields' => array('Field.id'), 'conditions' => array('OR' => array(array('Field.field_name LIKE' => '%Color%'), array('Field.field_name LIKE' => '%Colour%'))), 'order' => 'Field.id  asc', 'recursive' => '-1'));
                    $results = Set::extract('/Field/id', $color);
                    $colors_list = $this->ProductAdditionalFieldValue->find('all', array('fields' => array('ProductAdditionalFieldValue.values', 'count(ProductAdditionalFieldValue.values) as totalproduct'), 'conditions' => array('ProductAdditionalFieldValue.values !=' => '', 'ProductAdditionalFieldValue.product_id' => $p_list, 'ProductAdditionalFieldValue.field_id' => $results), 'order' => 'totalproduct desc', 'group' => 'ProductAdditionalFieldValue.values', 'recursive' => '-1'));
                    // pr($colors_list);
                }
            }

            $this->set('products', $this->Product->find('all', $prms));
        } else {
            echo 'invalid operation.';
            exit;
        }

        ///////////left-menu//////////////
        //pr($cat_list);
        $this->set('query', '');
        $this->set('search', 1);
        $this->set('item', $cat_list);
        $this->set('leftmenucolor', $colors_list);
        $this->set('leftmenustyle', $styles_list);
        $this->set('leftmenucondition', $conditions_list);
        $this->set('leftmenubrand', $brands_list);
        $this->set('leftmenusize', $sizes_list);
    }

    function browsebycategory($cat_id=null, $sort=null, $sort2=null) {
        $this->layout = 'innerhome';

        if (isset($this->params['url']['keywords']) && $this->params['url']['keywords'] != "") {
            $query1[0]['field'] = "Product.category_id";
            $query1[0]['value'] = $this->params['pass'][0];
            $query = base64_encode(serialize($query1));

            $no_push = 0;
            if (isset($this->params['url']['query']) && $this->params['url']['query'] != "") {
                $query2 = unserialize(base64_decode($this->params['url']['query']));

                $total_query2 = count($query2);
                $i = 0;

                foreach ($query2 as $query_val) {
                    if ($query_val['field'] == "Product.category_id") {
                        $query2[$i]['value'] = $this->params['pass'][0];
                        $no_push = 1;
                    }
                    $i++;
                }
                 if ($no_push == 0) {
                    $query2[$i]['field'] = "Product.category_id";
                    $query2[$i]['value'] = $this->params['pass'][0];
                    $no_push = 1;
                }
            }

            if ($no_push == 0) {
                $query2[0]['field'] = "Product.category_id";
                $query2[0]['value'] = $this->params['pass'][0];
            }
            $query = base64_encode(serialize($query2));


            $searchkey = explode(" ", $this->params['url']['keywords']);
            $this->set('searchkey', $this->params['url']['keywords']);
            $this->set('query', $query);
            for ($i = 0; $i < count($searchkey); $i++) {
                $p_title[$i] = "Product.products_title like '%" . $searchkey[$i] . "%'";
                $p_des[$i] = "Product.products_description like '%" . $searchkey[$i] . "%'";                       
            }
        } else {
            $searchkey = '';
            $this->set('query', '');
            $this->set('searchkey', '');
        }
        $this->set('item', $this->Category->categoryArray());
        $this->Product->Behaviors->attach('Containable');
        $this->Product->contain('User.username');
        $flds = array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.products_views', 'Product.products_price', 'Product.products_status', 'DATEDIFF(products_expiredDate,now()) AS totaldays');
        if ($sort == 2 || $sort2 == 2) {
            $fild = 'Product.products_createDate';
            $ord = 'DESC';
        } elseif ($sort == 3 || $sort2 == 3) {
            $fild = 'Product.products_price';
            $ord = 'DESC';
        } elseif ($sort == 4 || $sort2 == 4) {
            $fild = 'Product.products_price';
            $ord = 'ASC';
        } else {
            $fild = 'Product.products_expiredDate';
            $ord = 'ASC';
        }

        $category = $this->Category->viewAll($cat_id);
        $cat_ids[] = $cat_id;
        foreach ($category as $cat) {
            $cat_ids[] = $cat['id'];
        }

        $prms = array(
            'conditions' => array(
                'Product.category_id' => $cat_id,
                'OR' => array(array('Product.products_status !=' => 'Pending'),
                    array('Product.products_status !=' => 'Disapproved')),
                'Product.products_expiredDate >=' => date('Y-m-d H:i:s')),
            'order' => array($fild => $ord),
            'fields' => $flds,
            'contain' => array(
                'User.username',
                'Approver.username'
            )
        );

        if ($sort == "thumb") {
            $this->set('thumb', 'thumb');
            $this->Cookie->write('browseByCategoryView', 'thumb');
        } else {
            $this->Cookie->write('browseByCategoryView', 'default');
            $this->set('thumb', "");
        }
        $this->set('browseByCategoryViewCookie', $this->Cookie->read('browseByCategoryView'));

        $this->set('products', $this->Product->find('all', $prms));
        ///////////left-menu//////////////

        if ($searchkey) {
            $fld = "(";
            $and = 0;
            $colorid = "";
            $sizeid = "";
            $complete = "";
            if (isset($query2)) {
                foreach ($query2 as $fld_val) {
                    if ($and == 0) {
                        if ($fld_val['field'] == "color")
                            $colorid = $fld_val['value'];
                        if ($fld_val['field'] == "size")
                            $sizeid = $fld_val['value'];
                        if ($fld_val['field'] == "complete")
                            $complete = $fld_val['value'];
                        if ($fld_val['field'] == "price") {
                            $price = explode("|", $fld_val['value']);
                            $fld.='(Product.products_price BETWEEN ' . $price['0'] . ' AND ' . $price['1'] . ')';
                            $and = 1;
                        }
                        if (!in_array($fld_val['field'], array("color", "size", "complete", "price"))) {
                            $fld.=$fld_val['field'] . "=" . $fld_val['value'];
                            $and = 1;
                        }
                    } else {
                        if ($fld_val['field'] == "color")
                            $colorid = $fld_val['value'];
                        if ($fld_val['field'] == "size")
                            $sizeid = $fld_val['value'];
                        if ($fld_val['field'] == "complete")
                            $complete = $fld_val['value'];
                        if ($fld_val['field'] == "price") {
                            $price = explode("|", $fld_val['value']);
                            $fld.=' AND (Product.products_price BETWEEN ' . $price['0'] . ' AND ' . $price['1'] . ')';
                        }
                        if (!in_array($fld_val['field'], array("color", "size", "complete", "price"))) {
                            $fld.=" AND " . $fld_val['field'] . "=" . $fld_val['value'];
                        }
                    }
                }
            }

            if ($fld == "(")
                $fld.="1=1";
            $fld.=")";

            //Fetching product list
            $prms_p = array(
                'conditions' => array(
                    $fld,
                    'OR' => array(array('Product.products_status !=' => 'Pending'),
                        array('Product.products_status !=' => 'Disapproved')),
                    'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                    ),
                    'Product.products_expiredDate >=' => date('Y-m-d H:i:s')),
                'fields' => 'Product.id'
            );
            $productid_list = $this->Product->find('list', $prms_p);

            //Fetch Product id for color
            if ($colorid) {
                $productidlist = $this->ProductAdditionalFieldValue->find('all', array('fields' => array('ProductAdditionalFieldValue.product_id'), 'conditions' => array('ProductAdditionalFieldValue.product_id' => $productid_list, 'ProductAdditionalFieldValue.values' => $colorid), 'recursive' => '-1'));
                $productid_color = Set::extract('/ProductAdditionalFieldValue/product_id', $productidlist);
            }

            //Fetch Product id for size
            if ($sizeid) {
                $this->unbindModel(array('belongsTo' => array('Sizetitle', 'Sizelabel')));
                $allsizes = $this->find('all', array('fields' => array('ProductSize.product_id'), 'conditions' => array('ProductSize.product_id' => $productid_list, 'Sizevalue.size_value' => $sizeid)));
                $productid_size = Set::extract('/ProductSize/product_id', $allsizes);
            }

            //Intersect Product ID
            if (isset($productid_color) && isset($productid_size))
                $productid_list = array_intersect($productid_list, $productid_color, $productid_size);
            elseif (isset($productid_color))
                $productid_list = array_intersect($productid_list, $productid_color);
            elseif (isset($productid_size))
                $productid_list = array_intersect($productid_list, $productid_size);

            //Fetching products information
            $flds = array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.products_views', 'Product.products_price', 'Product.products_status', 'DATEDIFF(products_expiredDate,now()) AS totaldays');
            $prms = array(
                'conditions' => array(
                    'Product.id' => $productid_list,
                    'OR' => array(array('Product.products_status !=' => 'Pending'),
                        array('Product.products_status !=' => 'Disapproved')),
                    'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                    ),
                    'Product.products_expiredDate >=' => date('Y-m-d H:i:s')),
                'order' => array($fild => $ord),
                'fields' => $flds,
                'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
            );

            if ($complete == 'all') {
                $conditions = array('Cart.product_id' => $productid_list, 'Cart.order_id >' => 0, 'Cart.payment_status' => 1);
                $orders = array("Cart.add_date" => "DESC");
                $soldproductsid = $this->Cart->find('all', array("conditions" => $conditions, 'fields' => array('Cart.product_id'), 'order' => $orders, 'group' => 'Cart.product_id'));
                $soldproductsid = Set::extract('/Cart/product_id', $soldproductsid);
                $unsoldids = $this->Product->find('all', array('fields' => array('Product.id'), 'conditions' => array('Product.id' => $productid_list, 'Product.products_status' => 'Unsold', 'Product.unsold_date >' => date('Y-m-d', strtotime('-30 days')))));
                $unsoldids = Set::extract('/Product/id', $unsoldids);
                $productid_list = array_unique(array_merge($soldproductsid, $unsoldids));
                $prms = array(
                    'conditions' => array(
                        'Product.id' => $productid_list
                    ),
                    'order' => array($fild => $ord),
                    'fields' => $flds,
                    'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
                );
            } elseif ($complete == 'unsold') {
                $prms = array(
                    'conditions' => array(
                        'Product.id' => $productid_list,
                        'Product.products_status' => 'Unsold',
                        'Product.unsold_date >' => date('Y-m-d', strtotime('-30 days'))),
                    'order' => array($fild => $ord),
                    'fields' => $flds,
                    'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
                );
            } elseif ($complete == 'sold') {
                $conditions = array('Cart.product_id' => $productid_list, 'Cart.add_date >' => date('Y-m-d', strtotime('-30 days')), 'Cart.order_id >' => 0, 'Cart.payment_status' => 1);
                $orders = array("Cart.add_date" => "DESC");
                $soldproductsid = $this->Cart->find('all', array("conditions" => $conditions, 'fields' => array('Cart.product_id'), 'order' => $orders, 'group' => 'Cart.product_id'));
                $productid_list = Set::extract('/Cart/product_id', $soldproductsid);

                $prms = array(
                    'conditions' => array(
                        'Product.id' => $productid_list,
                    ),
                    'order' => array($fild => $ord),
                    'fields' => $flds,
                    'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
                );
            }

            //Fetching related category list
            $flds_cat = array('Product.category_id', 'count(Product.category_id) as total');
            $prms_cat = array(
                'conditions' => array(
                    'Product.id' => $productid_list,
                    'OR' => array(
                        array('Product.products_status !=' => 'Pending'),
                        array('Product.products_status !=' => 'Disapproved')
                    ),
                    'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                    ),
                    'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                ),
                'order' => 'total desc',
                'group' => 'Product.category_id',
                'fields' => $flds_cat
            );
            $this->Product->contain('Category.category_name');
            $cat_list = $this->Product->find('all', $prms_cat);

            //Fetching brand list
            $flds_brands = array('Product.global_brands', 'count(Product.global_brands) as totalproduct');
            $prms_brands = array(
                'conditions' => array(
                    'Product.id' => $productid_list,
                    'OR' => array(
                        array('Product.products_status !=' => 'Pending'),
                        array('Product.products_status !=' => 'Disapproved')
                    ),
                    'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                    ),
                    'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                ),
                'order' => 'totalproduct desc',
                'group' => 'Product.global_brands',
                'fields' => $flds_brands
            );
            $this->Product->contain('Brand.brand_description');
            $brands_list = $this->Product->find('all', $prms_brands);

            //Fetching condition list
            $flds_conditions = array('Product.global_conditions', 'count(Product.global_conditions) as totalproduct');
            $prms_conditions = array(
                'conditions' => array(
                    'Product.id' => $productid_list,
                    'OR' => array(
                        array('Product.products_status !=' => 'Pending'),
                        array('Product.products_status !=' => 'Disapproved')
                    ),
                    'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                    ),
                    'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                ),
                'order' => 'totalproduct desc',
                'group' => 'Product.global_conditions',
                'fields' => $flds_conditions
            );
            $this->Product->contain('ProductCondition.brand_description');
            $conditions_list = $this->Product->find('all', $prms_conditions);

            //Fetching style list
            $flds_styles = array('Product.global_styles', 'count(Product.global_styles) as totalproduct');
            $prms_styles = array(
                'conditions' => array(
                    'Product.id' => $productid_list,
                    'OR' => array(
                        array('Product.products_status !=' => 'Pending'),
                        array('Product.products_status !=' => 'Disapproved')
                    ),
                    'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                    ),
                    'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                ),
                'order' => 'totalproduct desc',
                'group' => 'Product.global_styles',
                'fields' => $flds_styles
            );
            $this->Product->contain('ProductStyle.brand_description');
            $styles_list = $this->Product->find('all', $prms_styles);

            //Fetching size list            
            $flds_sizes = array('Sizevalue.size_value');
            $prms_sizes = array(
                'conditions' => array(
                    'ProductSize.product_id' => $productid_list,
                ),
                'fields' => $flds_sizes,
                'group' => 'Sizevalue.size_value',
                'order' => 'Sizevalue.id asc'
            );
            $this->ProductSize->Behaviors->attach('Containable');
            $this->ProductSize->contain('Sizevalue');
            $sizes_list = $this->ProductSize->find('all', $prms_sizes);

            //Fetching Color list
            $color = $this->Field->find('all', array('fields' => array('Field.id'), 'conditions' => array('OR' => array(array('Field.field_name LIKE' => '%Color%'), array('Field.field_name LIKE' => '%Colour%'))), 'order' => 'Field.id  asc', 'recursive' => '-1'));
            $results = Set::extract('/Field/id', $color);
            $colors_list = $this->ProductAdditionalFieldValue->find('all', array('fields' => array('ProductAdditionalFieldValue.values', 'count(ProductAdditionalFieldValue.values) as totalproduct'), 'conditions' => array('ProductAdditionalFieldValue.values !=' => '', 'ProductAdditionalFieldValue.product_id' => $productid_list, 'ProductAdditionalFieldValue.field_id' => $results), 'order' => 'totalproduct desc', 'group' => 'ProductAdditionalFieldValue.values', 'recursive' => '-1'));

            //Set left sidbar menu
           
            $this->set('products', $this->Product->find('all', $prms));
            $this->set('item', $cat_list);
            $this->set('leftmenucolor', $colors_list);
            $this->set('leftmenustyle', $styles_list);
            $this->set('leftmenucondition', $conditions_list);
            $this->set('leftmenubrand', $brands_list);
            $this->set('leftmenusize', $sizes_list);
        } else {
            $this->set('leftmenucolor', $this->Field->color_menu());
            $this->set('leftmenustyle', $this->Product->brand_menu('global_styles'));
            $this->set('leftmenucondition', $this->Product->brand_menu('global_conditions'));
            $this->set('leftmenubrand', $this->Product->brand_menu('global_brands'));
            $this->set('leftmenusize', $this->ProductSize->size_menu());
        }
    }

    function browsebybrand($id=null, $type=null, $sort=null, $sort2=null) {
        $this->layout = 'innerhome';

        if (isset($this->params['url']['keywords']) && $this->params['url']['keywords'] != "") {
            $query1[0]['field'] = $this->params['pass'][1];
            $query1[0]['value'] = $this->params['pass'][0];
            $query = base64_encode(serialize($query1));

            $no_push = 0;
            if (isset($this->params['url']['query']) && $this->params['url']['query'] != "") {
                $query2 = unserialize(base64_decode($this->params['url']['query']));

                $total_query2 = count($query2);
                $i = 0;

                foreach ($query2 as $query_val) {
                    if ($query_val['field'] == $this->params['pass'][1]) {
                        $query2[$i]['value'] = $this->params['pass'][0];
                        $no_push = 1;
                    }
                    $i++;
                }
                 if ($no_push == 0) {
                    $query2[$i]['field'] = $this->params['pass'][1];
                    $query2[$i]['value'] = $this->params['pass'][0];
                    $no_push = 1;
                }
            }

            if ($no_push == 0) {
                $query2[0]['field'] = $this->params['pass'][1];
                $query2[0]['value'] = $this->params['pass'][0];
            }
            $query = base64_encode(serialize($query2));


            $searchkey = explode(" ", $this->params['url']['keywords']);
            $this->set('searchkey', $this->params['url']['keywords']);
            $this->set('query', $query);
            for ($i = 0; $i < count($searchkey); $i++) {
                $p_title[$i] = "Product.products_title like '%" . $searchkey[$i] . "%'";
                $p_des[$i] = "Product.products_description like '%" . $searchkey[$i] . "%'";                       
            }
        } else {
            $searchkey = '';
            $this->set('query', '');
            $this->set('searchkey', '');
        }
        $this->set('item', $this->Category->categoryArray());
        $categories = $this->Product->Category->find('list');
        $this->set(compact('categories'));
        $this->Product->Behaviors->attach('Containable');
        $this->Product->contain('User.username');
        $flds = array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.products_views', 'Product.products_price', 'Product.products_status', 'DATEDIFF(products_expiredDate,now()) AS totaldays');
        $fieldtype = 'Product.' . $type;
        if ($sort == 2 || $sort2 == 2) {
            $fild = 'Product.products_createDate';
            $ord = 'DESC';
        } elseif ($sort == 3 || $sort2 == 3) {
            $fild = 'Product.products_price';
            $ord = 'DESC';
        } elseif ($sort == 4 || $sort2 == 4) {
            $fild = 'Product.products_price';
            $ord = 'ASC';
        } else {
            $fild = 'Product.products_expiredDate';
            $ord = 'ASC';
        }

        $prms = array(
            'conditions' => array(
                $type => $id,
                'OR' => array(array('Product.products_status !=' => 'Pending'),
                    array('Product.products_status !=' => 'Disapproved')),                
                'Product.products_expiredDate >=' => date('Y-m-d H:i:s')),
            'order' => array($fild => $ord),
            'fields' => $flds,
            'contain' => array(
                'User.username',
                'Approver.username'
            )
        );
        if ($sort == "thumb") {
            $this->set('thumb', 'thumb');
            if ($type == "global_brands")
                $this->Cookie->write('browseByBrandView', 'thumb');
            if ($type == "global_styles")
                $this->Cookie->write('browseByStyleView', 'thumb');
            if ($type == "global_conditions")
                $this->Cookie->write('browseByConditionView', 'thumb');
        } else {
            if ($type == "global_brands")
                $this->Cookie->write('browseByBrandView', 'default');
            if ($type == "global_styles")
                $this->Cookie->write('browseByStyleView', 'default');
            if ($type == "global_conditions")
                $this->Cookie->write('browseByConditionView', 'default');
            $this->set('thumb', "");
        }
        $this->set('browseByBrandViewCookie', $this->Cookie->read('browseByBrandView'));
        $this->set('browseByStyleViewCookie', $this->Cookie->read('browseByStyleView'));
        $this->set('browseByConditionViewCookie', $this->Cookie->read('browseByCOnditionView'));

        $this->set('products', $this->Product->find('all', $prms));
        $this->set('brandname', $this->Brand->read('brand_description', $id));

        ///////////left-menu//////////////      
        if ($searchkey) {
            $fld = "(";
            $and = 0;
            $colorid = "";
            $sizeid = "";
            $complete = "";
            if (isset($query2)) {
                foreach ($query2 as $fld_val) {
                    if ($and == 0) {
                        if ($fld_val['field'] == "color")
                            $colorid = $fld_val['value'];
                        if ($fld_val['field'] == "size")
                            $sizeid = $fld_val['value'];
                        if ($fld_val['field'] == "complete")
                            $complete = $fld_val['value'];
                        if ($fld_val['field'] == "price") {
                            $price = explode("|", $fld_val['value']);
                            $fld.='(Product.products_price BETWEEN ' . $price['0'] . ' AND ' . $price['1'] . ')';
                            $and = 1;
                        }
                        if (!in_array($fld_val['field'], array("color", "size", "complete", "price"))) {
                            $fld.=$fld_val['field'] . "=" . $fld_val['value'];
                            $and = 1;
                        }
                    } else {
                        if ($fld_val['field'] == "color")
                            $colorid = $fld_val['value'];
                        if ($fld_val['field'] == "size")
                            $sizeid = $fld_val['value'];
                        if ($fld_val['field'] == "complete")
                            $complete = $fld_val['value'];
                        if ($fld_val['field'] == "price") {
                            $price = explode("|", $fld_val['value']);
                            $fld.=' AND (Product.products_price BETWEEN ' . $price['0'] . ' AND ' . $price['1'] . ')';
                        }
                        if (!in_array($fld_val['field'], array("color", "size", "complete", "price"))) {
                            $fld.=" AND " . $fld_val['field'] . "=" . $fld_val['value'];
                        }
                    }
                }
            }

            if ($fld == "(")
                $fld.="1=1";
            $fld.=")";

            //Fetching product list
            $prms_p = array(
                'conditions' => array(
                    $fld,
                    'OR' => array(array('Product.products_status !=' => 'Pending'),
                        array('Product.products_status !=' => 'Disapproved')),
                    'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                    ),
                    'Product.products_expiredDate >=' => date('Y-m-d H:i:s')),
                
                'fields' => 'Product.id'
            );
            $productid_list = $this->Product->find('list', $prms_p);

            //Fetch Product id for color
            if ($colorid) {
                $productidlist = $this->ProductAdditionalFieldValue->find('all', array('fields' => array('ProductAdditionalFieldValue.product_id'), 'conditions' => array('ProductAdditionalFieldValue.product_id' => $productid_list, 'ProductAdditionalFieldValue.values' => $colorid), 'recursive' => '-1'));
                $productid_color = Set::extract('/ProductAdditionalFieldValue/product_id', $productidlist);
            }

            //Fetch Product id for size
            if ($sizeid) {
                $this->unbindModel(array('belongsTo' => array('Sizetitle', 'Sizelabel')));
                $allsizes = $this->find('all', array('fields' => array('ProductSize.product_id'), 'conditions' => array('ProductSize.product_id' => $productid_list, 'Sizevalue.size_value' => $sizeid)));
                $productid_size = Set::extract('/ProductSize/product_id', $allsizes);
            }

            //Intersect Product ID
            if (isset($productid_color) && isset($productid_size))
                $productid_list = array_intersect($productid_list, $productid_color, $productid_size);
            elseif (isset($productid_color))
                $productid_list = array_intersect($productid_list, $productid_color);
            elseif (isset($productid_size))
                $productid_list = array_intersect($productid_list, $productid_size);

            //Fetching products information
            $flds = array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.products_views', 'Product.products_price', 'Product.products_status', 'DATEDIFF(products_expiredDate,now()) AS totaldays');
            $prms = array(
                'conditions' => array(
                    'Product.id' => $productid_list,
                    'OR' => array(array('Product.products_status !=' => 'Pending'),
                        array('Product.products_status !=' => 'Disapproved')),
                    'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                    ),
                    'Product.products_expiredDate >=' => date('Y-m-d H:i:s')),
                'order' => array($fild => $ord),
                'fields' => $flds,
                'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
            );

            if ($complete == 'all') {
                $conditions = array('Cart.product_id' => $productid_list, 'Cart.order_id >' => 0, 'Cart.payment_status' => 1);
                $orders = array("Cart.add_date" => "DESC");
                $soldproductsid = $this->Cart->find('all', array("conditions" => $conditions, 'fields' => array('Cart.product_id'), 'order' => $orders, 'group' => 'Cart.product_id'));
                $soldproductsid = Set::extract('/Cart/product_id', $soldproductsid);
                $unsoldids = $this->Product->find('all', array('fields' => array('Product.id'), 'conditions' => array('Product.id' => $productid_list, 'Product.products_status' => 'Unsold', 'Product.unsold_date >' => date('Y-m-d', strtotime('-30 days')))));
                $unsoldids = Set::extract('/Product/id', $unsoldids);
                $productid_list = array_unique(array_merge($soldproductsid, $unsoldids));
                $prms = array(
                    'conditions' => array(
                        'Product.id' => $productid_list
                    ),
                    'order' => array($fild => $ord),
                    'fields' => $flds,
                    'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
                );
            } elseif ($complete == 'unsold') {
                $prms = array(
                    'conditions' => array(
                        'Product.id' => $productid_list,
                        'Product.products_status' => 'Unsold',
                        'Product.unsold_date >' => date('Y-m-d', strtotime('-30 days'))),
                    'order' => array($fild => $ord),
                    'fields' => $flds,
                    'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
                );
            } elseif ($complete == 'sold') {
                $conditions = array('Cart.product_id' => $productid_list, 'Cart.add_date >' => date('Y-m-d', strtotime('-30 days')), 'Cart.order_id >' => 0, 'Cart.payment_status' => 1);
                $orders = array("Cart.add_date" => "DESC");
                $soldproductsid = $this->Cart->find('all', array("conditions" => $conditions, 'fields' => array('Cart.product_id'), 'order' => $orders, 'group' => 'Cart.product_id'));
                $productid_list = Set::extract('/Cart/product_id', $soldproductsid);

                $prms = array(
                    'conditions' => array(
                        'Product.id' => $productid_list,
                    ),
                    'order' => array($fild => $ord),
                    'fields' => $flds,
                    'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
                );
            }

            //Fetching related category list
            $flds_cat = array('Product.category_id', 'count(Product.category_id) as total');
            $prms_cat = array(
                'conditions' => array(
                    'Product.id' => $productid_list,
                    'OR' => array(
                        array('Product.products_status !=' => 'Pending'),
                        array('Product.products_status !=' => 'Disapproved')
                    ),
                    'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                    ),
                    'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                ),
                'order' => 'total desc',
                'group' => 'Product.category_id',
                'fields' => $flds_cat
            );
            $this->Product->contain('Category.category_name');
            $cat_list = $this->Product->find('all', $prms_cat);

            //Fetching brand list
            $flds_brands = array('Product.global_brands', 'count(Product.global_brands) as totalproduct');
            $prms_brands = array(
                'conditions' => array(
                    'Product.id' => $productid_list,
                    'OR' => array(
                        array('Product.products_status !=' => 'Pending'),
                        array('Product.products_status !=' => 'Disapproved')
                    ),
                    'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                    ),
                    'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                ),
                'order' => 'totalproduct desc',
                'group' => 'Product.global_brands',
                'fields' => $flds_brands
            );
            $this->Product->contain('Brand.brand_description');
            $brands_list = $this->Product->find('all', $prms_brands);

            //Fetching condition list
            $flds_conditions = array('Product.global_conditions', 'count(Product.global_conditions) as totalproduct');
            $prms_conditions = array(
                'conditions' => array(
                    'Product.id' => $productid_list,
                    'OR' => array(
                        array('Product.products_status !=' => 'Pending'),
                        array('Product.products_status !=' => 'Disapproved')
                    ),
                    'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                    ),
                    'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                ),
                'order' => 'totalproduct desc',
                'group' => 'Product.global_conditions',
                'fields' => $flds_conditions
            );
            $this->Product->contain('ProductCondition.brand_description');
            $conditions_list = $this->Product->find('all', $prms_conditions);

            //Fetching style list
            $flds_styles = array('Product.global_styles', 'count(Product.global_styles) as totalproduct');
            $prms_styles = array(
                'conditions' => array(
                    'Product.id' => $productid_list,
                    'OR' => array(
                        array('Product.products_status !=' => 'Pending'),
                        array('Product.products_status !=' => 'Disapproved')
                    ),
                    'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                    ),
                    'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                ),
                'order' => 'totalproduct desc',
                'group' => 'Product.global_styles',
                'fields' => $flds_styles
            );
            $this->Product->contain('ProductStyle.brand_description');
            $styles_list = $this->Product->find('all', $prms_styles);

            //Fetching size list            
            $flds_sizes = array('Sizevalue.size_value');
            $prms_sizes = array(
                'conditions' => array(
                    'ProductSize.product_id' => $productid_list,
                ),
                'fields' => $flds_sizes,
                'group' => 'Sizevalue.size_value',
                'order' => 'Sizevalue.id asc'
            );
            $this->ProductSize->Behaviors->attach('Containable');
            $this->ProductSize->contain('Sizevalue');
            $sizes_list = $this->ProductSize->find('all', $prms_sizes);

            //Fetching Color list
            $color = $this->Field->find('all', array('fields' => array('Field.id'), 'conditions' => array('OR' => array(array('Field.field_name LIKE' => '%Color%'), array('Field.field_name LIKE' => '%Colour%'))), 'order' => 'Field.id  asc', 'recursive' => '-1'));
            $results = Set::extract('/Field/id', $color);
            $colors_list = $this->ProductAdditionalFieldValue->find('all', array('fields' => array('ProductAdditionalFieldValue.values', 'count(ProductAdditionalFieldValue.values) as totalproduct'), 'conditions' => array('ProductAdditionalFieldValue.values !=' => '', 'ProductAdditionalFieldValue.product_id' => $productid_list, 'ProductAdditionalFieldValue.field_id' => $results), 'order' => 'totalproduct desc', 'group' => 'ProductAdditionalFieldValue.values', 'recursive' => '-1'));

            //Set left sidbar menu

            $this->set('products', $this->Product->find('all', $prms));
            $this->set('item', $cat_list);
            $this->set('leftmenucolor', $colors_list);
            $this->set('leftmenustyle', $styles_list);
            $this->set('leftmenucondition', $conditions_list);
            $this->set('leftmenubrand', $brands_list);
            $this->set('leftmenusize', $sizes_list);
        } else {
            $this->set('leftmenucolor', $this->Field->color_menu());
            $this->set('leftmenustyle', $this->Product->brand_menu('global_styles'));
            $this->set('leftmenucondition', $this->Product->brand_menu('global_conditions'));
            $this->set('leftmenubrand', $this->Product->brand_menu('global_brands'));
            $this->set('leftmenusize', $this->ProductSize->size_menu());
        }
    }

    function browsebycompletedlist($type=null, $sort=null, $sort2=null) {
        $this->layout = 'innerhome';
        if (isset($this->params['url']['keywords']) && $this->params['url']['keywords'] != "") {
            $query1[0]['field'] = "complete";
            $query1[0]['value'] = $type;
            $query = base64_encode(serialize($query1));

            $no_push = 0;
            if (isset($this->params['url']['query']) && $this->params['url']['query'] != "") {
                $query2 = unserialize(base64_decode($this->params['url']['query']));

                $total_query2 = count($query2);
                $i = 0;
                foreach ($query2 as $query_val) {
                    if ($query_val['field'] == "complete") {
                        $query2[$i]['value'] = $type;
                        $no_push = 1;
                    }
                    $i++;
                }
                 if ($no_push == 0) {
                    $query2[$i]['field'] = "complete";
                    $query2[$i]['value'] = $type;
                    $no_push = 1;
                }
            }

            if ($no_push == 0) {
                $query2[0]['field'] = "complete";
                $query2[0]['value'] = $type;
            }
            $query = base64_encode(serialize($query2));

            $searchkey = explode(" ", $this->params['url']['keywords']);
            $this->set('searchkey', $this->params['url']['keywords']);
            $this->set('query', $query);
            for ($i = 0; $i < count($searchkey); $i++) {
                $p_title[$i] = "Product.products_title like '%" . $searchkey[$i] . "%'";
                $p_des[$i] = "Product.products_description like '%" . $searchkey[$i] . "%'";                       
            }
        } else {
            $searchkey = '';
            $this->set('query', '');
            $this->set('searchkey', '');
        }
        $this->set('item', $this->Category->categoryArray());
        $categories = $this->Product->Category->find('list');
        $this->set(compact('categories'));
        $this->Product->Behaviors->attach('Containable');
        $this->Product->contain('User.username');
        $flds = array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.products_views', 'Product.products_price', 'Product.products_status', 'DATEDIFF(products_expiredDate,now()) AS totaldays');
        if ($sort == 2 || $sort2 == 2) {
            $fild = 'Product.products_createDate';
            $ord = 'DESC';
        } elseif ($sort == 3 || $sort2 == 3) {
            $fild = 'Product.products_price';
            $ord = 'DESC';
        } elseif ($sort == 4 || $sort2 == 4) {
            $fild = 'Product.products_price';
            $ord = 'ASC';
        } else {
            $fild = 'Product.products_expiredDate';
            $ord = 'ASC';
        }
        if ($type == 'all') {
            $conditions = array('Cart.order_id >' => 0, 'Cart.payment_status' => 1);
            $orders = array("Cart.add_date" => "DESC");
            $soldproductsid = $this->Cart->find('all', array("conditions" => $conditions, 'fields' => array('Cart.product_id'), 'order' => $orders, 'group' => 'Cart.product_id'));
            $soldproductsid = Set::extract('/Cart/product_id', $soldproductsid);
            $unsoldids = $this->Product->find('all', array('fields' => array('Product.id'), 'conditions' => array('Product.products_status' => 'Unsold', 'Product.unsold_date >' => date('Y-m-d', strtotime('-30 days')))));
            $unsoldids = Set::extract('/Product/id', $unsoldids);

            $prms = array(
                'conditions' => array(
                    'Product.id' => array_unique(array_merge($soldproductsid, $unsoldids))),
                'order' => array($fild => $ord),
                'fields' => $flds,
                'contain' => array(
                    'User.username',
                    'Approver.username'
                )
            );
        } elseif ($type == 'unsold') {
            $prms = array(
                'conditions' => array(
                    'Product.products_status' => 'Unsold',
                    'Product.unsold_date >' => date('Y-m-d', strtotime('-30 days'))),
                'order' => array($fild => $ord),
                'fields' => $flds,
                'contain' => array(
                    'User.username',
                    'Approver.username'
                )
            );
        } elseif ($type == 'sold') {

            $conditions = array('Cart.add_date >' => date('Y-m-d', strtotime('-30 days')), 'Cart.order_id >' => 0, 'Cart.payment_status' => 1);
            $orders = array("Cart.add_date" => "DESC");
            $soldproductsid = $this->Cart->find('all', array("conditions" => $conditions, 'fields' => array('Cart.product_id'), 'order' => $orders, 'group' => 'Cart.product_id'));
            $soldproductsid = Set::extract('/Cart/product_id', $soldproductsid);

            $prms = array(
                'conditions' => array(
                    'Product.id' => $soldproductsid,
                ),
                'order' => array($fild => $ord),
                'fields' => $flds,
                'contain' => array(
                    'User.username',
                    'Approver.username'
                )
            );
        }

        if ($sort == "thumb") {
            $this->set('thumb', 'thumb');
            if ($type == 'sold')
                $this->Cookie->write('browseBySoldView', 'thumb');
            if ($type == 'unsold')
                $this->Cookie->write('browseByUnsoldView', 'thumb');
            if ($type == 'all')
                $this->Cookie->write('browseByAllView', 'thumb');
        } else {
            if ($type == 'sold')
                $this->Cookie->write('browseBySoldView', 'default');
            if ($type == 'unsold')
                $this->Cookie->write('browseByUnsoldView', 'default');
            if ($type == 'all')
                $this->Cookie->write('browseByAllView', 'default');
            $this->set('thumb', "");
        }
        $this->set('browseBySoldViewCookie', $this->Cookie->read('browseBySoldView'));
        $this->set('browseByUnsoldViewCookie', $this->Cookie->read('browseByUnsoldView'));
        $this->set('browseByAllViewCookie', $this->Cookie->read('browseByAllView'));

        $this->set('products', $this->Product->find('all', $prms));
        $this->set('type', $type);
        ///////////left-menu//////////////
        if ($searchkey) {
            $fld = "(";
            $and = 0;
            $colorid = "";
            $sizeid = "";
            if (isset($query2)) {
                foreach ($query2 as $fld_val) {
                    if ($and == 0) {
                        if ($fld_val['field'] == "color")
                            $colorid = $fld_val['value'];
                        if ($fld_val['field'] == "size")
                            $sizeid = $fld_val['value'];
                        if ($fld_val['field'] == "complete")
                            $complete = $fld_val['value'];
                        if ($fld_val['field'] == "price") {
                            $price = explode("|", $fld_val['value']);
                            $fld.='(Product.products_price BETWEEN ' . $price['0'] . ' AND ' . $price['1'] . ')';
                            $and = 1;
                        }
                        if (!in_array($fld_val['field'], array("color", "size", "complete", "price"))) {
                            $fld.=$fld_val['field'] . "=" . $fld_val['value'];
                            $and = 1;
                        }
                    } else {
                        if ($fld_val['field'] == "color")
                            $colorid = $fld_val['value'];
                        if ($fld_val['field'] == "size")
                            $sizeid = $fld_val['value'];
                        if ($fld_val['field'] == "complete")
                            $complete = $fld_val['value'];
                        if ($fld_val['field'] == "price") {
                            $price = explode("|", $fld_val['value']);
                            $fld.=' AND (Product.products_price BETWEEN ' . $price['0'] . ' AND ' . $price['1'] . ')';
                        }
                        if (!in_array($fld_val['field'], array("color", "size", "complete", "price"))) {
                            $fld.=" AND " . $fld_val['field'] . "=" . $fld_val['value'];
                        }
                    }
                }
            }

            if ($fld == "(")
                $fld.="1=1";
            $fld.=")";

            //Fetching product list
            $prms_p = array(
                'conditions' => array(
                    $fld,
                    'OR' => array(array('Product.products_status !=' => 'Pending'),
                        array('Product.products_status !=' => 'Disapproved')),
                    'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                    ),
                    'Product.products_expiredDate >=' => date('Y-m-d H:i:s')),
                'fields' => 'Product.id'
            );
            $productid_list = $this->Product->find('list', $prms_p);

            //Fetch Product id for color
            if ($colorid) {
                $productidlist = $this->ProductAdditionalFieldValue->find('all', array('fields' => array('ProductAdditionalFieldValue.product_id'), 'conditions' => array('ProductAdditionalFieldValue.product_id' => $productid_list, 'ProductAdditionalFieldValue.values' => $colorid), 'recursive' => '-1'));
                $productid_color = Set::extract('/ProductAdditionalFieldValue/product_id', $productidlist);
            }

            //Fetch Product id for size
            if ($sizeid) {
                $this->unbindModel(array('belongsTo' => array('Sizetitle', 'Sizelabel')));
                $allsizes = $this->find('all', array('fields' => array('ProductSize.product_id'), 'conditions' => array('ProductSize.product_id' => $productid_list, 'Sizevalue.size_value' => $sizeid)));
                $productid_size = Set::extract('/ProductSize/product_id', $allsizes);
            }

            //Intersect Product ID
            if (isset($productid_color) && isset($productid_size))
                $productid_list = array_intersect($productid_list, $productid_color, $productid_size);
            elseif (isset($productid_color))
                $productid_list = array_intersect($productid_list, $productid_color);
            elseif (isset($productid_size))
                $productid_list = array_intersect($productid_list, $productid_size);

            //Fetching products information
            $flds = array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.products_views', 'Product.products_price', 'Product.products_status', 'DATEDIFF(products_expiredDate,now()) AS totaldays');
            $prms = array(
                'conditions' => array(
                    'Product.id' => $productid_list,
                    'OR' => array(array('Product.products_status !=' => 'Pending'),
                        array('Product.products_status !=' => 'Disapproved')),
                    'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                    ),
                    'Product.products_expiredDate >=' => date('Y-m-d H:i:s')),
                'fields' => $flds,
                'order' => array($fild => $ord),
                'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
            );

            if ($complete == 'all') {
                $conditions = array('Cart.product_id' => $productid_list, 'Cart.order_id >' => 0, 'Cart.payment_status' => 1);
                $orders = array("Cart.add_date" => "DESC");
                $soldproductsid = $this->Cart->find('all', array("conditions" => $conditions, 'fields' => array('Cart.product_id'), 'order' => $orders, 'group' => 'Cart.product_id'));
                $soldproductsid = Set::extract('/Cart/product_id', $soldproductsid);
                $unsoldids = $this->Product->find('all', array('fields' => array('Product.id'), 'conditions' => array('Product.id' => $productid_list, 'Product.products_status' => 'Unsold', 'Product.unsold_date >' => date('Y-m-d', strtotime('-30 days')))));
                $unsoldids = Set::extract('/Product/id', $unsoldids);
                $productid_list = array_unique(array_merge($soldproductsid, $unsoldids));
                $prms = array(
                    'conditions' => array(
                        'Product.id' => $productid_list
                    ),
                    'order' => array($fild => $ord),
                    'fields' => $flds,
                    'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
                );
            } elseif ($complete == 'unsold') {
                $prms = array(
                    'conditions' => array(
                        'Product.id' => $productid_list,
                        'Product.products_status' => 'Unsold',
                        'Product.unsold_date >' => date('Y-m-d', strtotime('-30 days'))),
                    'order' => array($fild => $ord),
                    'fields' => $flds,
                    'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
                );
            } elseif ($complete == 'sold') {
                $conditions = array('Cart.product_id' => $productid_list, 'Cart.add_date >' => date('Y-m-d', strtotime('-30 days')), 'Cart.order_id >' => 0, 'Cart.payment_status' => 1);
                $orders = array("Cart.add_date" => "DESC");
                $soldproductsid = $this->Cart->find('all', array("conditions" => $conditions, 'fields' => array('Cart.product_id'), 'order' => $orders, 'group' => 'Cart.product_id'));
                $productid_list = Set::extract('/Cart/product_id', $soldproductsid);

                $prms = array(
                    'conditions' => array(
                        'Product.id' => $productid_list,
                    ),
                    'order' => array($fild => $ord),
                    'fields' => $flds,
                    'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
                );
            }

            //Fetching related category list
            $flds_cat = array('Product.category_id', 'count(Product.category_id) as total');
            $prms_cat = array(
                'conditions' => array(
                    'Product.id' => $productid_list,
                    'OR' => array(
                        array('Product.products_status !=' => 'Pending'),
                        array('Product.products_status !=' => 'Disapproved')
                    ),
                    'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                    ),
                    'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                ),
                'order' => 'total desc',
                'group' => 'Product.category_id',
                'fields' => $flds_cat
            );
            $this->Product->contain('Category.category_name');
            $cat_list = $this->Product->find('all', $prms_cat);

            //Fetching brand list
            $flds_brands = array('Product.global_brands', 'count(Product.global_brands) as totalproduct');
            $prms_brands = array(
                'conditions' => array(
                    'Product.id' => $productid_list,
                    'OR' => array(
                        array('Product.products_status !=' => 'Pending'),
                        array('Product.products_status !=' => 'Disapproved')
                    ),
                    'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                    ),
                    'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                ),
                'order' => 'totalproduct desc',
                'group' => 'Product.global_brands',
                'fields' => $flds_brands
            );
            $this->Product->contain('Brand.brand_description');
            $brands_list = $this->Product->find('all', $prms_brands);

            //Fetching condition list
            $flds_conditions = array('Product.global_conditions', 'count(Product.global_conditions) as totalproduct');
            $prms_conditions = array(
                'conditions' => array(
                    'Product.id' => $productid_list,
                    'OR' => array(
                        array('Product.products_status !=' => 'Pending'),
                        array('Product.products_status !=' => 'Disapproved')
                    ),
                    'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                    ),
                    'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                ),
                'order' => 'totalproduct desc',
                'group' => 'Product.global_conditions',
                'fields' => $flds_conditions
            );
            $this->Product->contain('ProductCondition.brand_description');
            $conditions_list = $this->Product->find('all', $prms_conditions);

            //Fetching style list
            $flds_styles = array('Product.global_styles', 'count(Product.global_styles) as totalproduct');
            $prms_styles = array(
                'conditions' => array(
                    'Product.id' => $productid_list,
                    'OR' => array(
                        array('Product.products_status !=' => 'Pending'),
                        array('Product.products_status !=' => 'Disapproved')
                    ),
                    'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                    ),
                    'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                ),
                'order' => 'totalproduct desc',
                'group' => 'Product.global_styles',
                'fields' => $flds_styles
            );
            $this->Product->contain('ProductStyle.brand_description');
            $styles_list = $this->Product->find('all', $prms_styles);

            //Fetching size list            
            $flds_sizes = array('Sizevalue.size_value');
            $prms_sizes = array(
                'conditions' => array(
                    'ProductSize.product_id' => $productid_list,
                ),
                'fields' => $flds_sizes,
                'group' => 'Sizevalue.size_value',
                'order' => 'Sizevalue.id asc'
            );
            $this->ProductSize->Behaviors->attach('Containable');
            $this->ProductSize->contain('Sizevalue');
            $sizes_list = $this->ProductSize->find('all', $prms_sizes);

            //Fetching Color list
            $color = $this->Field->find('all', array('fields' => array('Field.id'), 'conditions' => array('OR' => array(array('Field.field_name LIKE' => '%Color%'), array('Field.field_name LIKE' => '%Colour%'))), 'order' => 'Field.id  asc', 'recursive' => '-1'));
            $results = Set::extract('/Field/id', $color);
            $colors_list = $this->ProductAdditionalFieldValue->find('all', array('fields' => array('ProductAdditionalFieldValue.values', 'count(ProductAdditionalFieldValue.values) as totalproduct'), 'conditions' => array('ProductAdditionalFieldValue.values !=' => '', 'ProductAdditionalFieldValue.product_id' => $productid_list, 'ProductAdditionalFieldValue.field_id' => $results), 'order' => 'totalproduct desc', 'group' => 'ProductAdditionalFieldValue.values', 'recursive' => '-1'));

            //Set left sidbar menu
            $this->set('products', $this->Product->find('all', $prms));
            $this->set('item', $cat_list);
            $this->set('leftmenucolor', $colors_list);
            $this->set('leftmenustyle', $styles_list);
            $this->set('leftmenucondition', $conditions_list);
            $this->set('leftmenubrand', $brands_list);
            $this->set('leftmenusize', $sizes_list);
        } else {
            $this->set('leftmenucolor', $this->Field->color_menu());
            $this->set('leftmenustyle', $this->Product->brand_menu('global_styles'));
            $this->set('leftmenucondition', $this->Product->brand_menu('global_conditions'));
            $this->set('leftmenubrand', $this->Product->brand_menu('global_brands'));
            $this->set('leftmenusize', $this->ProductSize->size_menu());
        }
    }

    function browsebyprice($price1=null, $price2=null, $sort=null, $sort2=null) {
        $this->layout = 'innerhome';

        if (isset($this->params['url']['keywords']) && $this->params['url']['keywords'] != "") {
            $query1[0]['field'] = "price";
            $query1[0]['value'] = $_POST['price1'] . "|" . $_POST['price2'];
            $query = base64_encode(serialize($query1));

            $no_push = 0;
            if (isset($this->params['url']['query']) && $this->params['url']['query'] != "") {
                $query2 = unserialize(base64_decode($this->params['url']['query']));

                $total_query2 = count($query2);
                $i = 0;

                foreach ($query2 as $query_val) {
                    if ($query_val['field'] == "price") {
                        $query2[$i]['value'] = $_POST['price1'] . "|" . $_POST['price2'];
                        $no_push = 1;
                    }
                    $i++;
                }
                if ($no_push == 0) {
                    $query2[$i]['field'] = "price";
                    $query2[$i]['value'] = $_POST['price1'] . "|" . $_POST['price2'];
                    $no_push = 1;
                }
            }
            if ($no_push == 0) {
                $query2[0]['field'] = "price";
                $query2[0]['value'] = $_POST['price1'] . "|" . $_POST['price2'];
            }
            $query = base64_encode(serialize($query2));


            $searchkey = explode(" ", $this->params['url']['keywords']);
            $this->set('searchkey', $this->params['url']['keywords']);
            $this->set('query', $query);
            for ($i = 0; $i < count($searchkey); $i++) {
                $p_title[$i] = "Product.products_title like '%" . $searchkey[$i] . "%'";
                $p_des[$i] = "Product.products_description like '%" . $searchkey[$i] . "%'";                       
            }
        } else {
            $searchkey = '';
            $this->set('query', '');
            $this->set('searchkey', '');
        }
        $this->set('item', $this->Category->categoryArray());
        //$this->set('homePageContent', $this->Product->homePageProducts($this->Category->randomCategory()));
        $categories = $this->Product->Category->find('list');
        $this->set(compact('categories'));
        $this->Product->Behaviors->attach('Containable');
        $this->Product->contain('User.username');
        $flds = array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.products_views', 'Product.products_price', 'Product.products_status', 'DATEDIFF(products_expiredDate,now()) AS totaldays');
        if ($sort == 2 || $sort2 == 2) {
            $fild = 'Product.products_createDate';
            $ord = 'DESC';
        } elseif ($sort == 3 || $sort2 == 3) {
            $fild = 'Product.products_price';
            $ord = 'DESC';
        } elseif ($sort == 4 || $sort2 == 4) {
            $fild = 'Product.products_price';
            $ord = 'ASC';
        } else {
            $fild = 'Product.products_expiredDate';
            $ord = 'ASC';
        }

        if (isset($_POST['price1'])) {
            $price1 = $_POST['price1'];
            $price2 = $_POST['price2'];
        }

        $prms = array(
            'conditions' => array(
                'Product.products_price BETWEEN ? AND ?' => array($price1, $price2),
                'OR' => array(array('Product.products_status !=' => 'Pending'),
                    array('Product.products_status !=' => 'Disapproved')),
                'Product.products_expiredDate >=' => date('Y-m-d H:i:s')),
            'order' => array($fild => $ord),
            'fields' => $flds,
            'contain' => array(
                'User.username',
                'Approver.username'
            )
        );
        if ($sort == "thumb")
            $this->set('thumb', "thumb");
        $this->set('products', $this->Product->find('all', $prms));
        $this->set('price1', $price1);
        $this->set('price2', $price2);
        ///////////left-menu//////////////
        if ($searchkey) {
            $fld = "(";
            $and = 0;
            $colorid = "";
            $sizeid = "";
            $complete = "";
            
            if (isset($query2)) {
                foreach ($query2 as $fld_val) {
                    if ($and == 0) {
                        if ($fld_val['field'] == "color")
                            $colorid = $fld_val['value'];
                        if ($fld_val['field'] == "size")
                            $sizeid = $fld_val['value'];
                        if ($fld_val['field'] == "complete")
                            $complete = $fld_val['value'];
                        if ($fld_val['field'] == "price") {
                            $price = explode("|", $fld_val['value']);                            
                            $fld.='(Product.products_price BETWEEN ' . $price['0'] . ' AND ' . $price['1'] . ')';
                            $and = 1;
                        }
                        if (!in_array($fld_val['field'], array("color", "size", "complete", "price"))) {
                            $fld.=$fld_val['field'] . "=" . $fld_val['value'];
                            $and = 1;
                        }
                    } else {
                        if ($fld_val['field'] == "color")
                            $colorid = $fld_val['value'];
                        if ($fld_val['field'] == "size")
                            $sizeid = $fld_val['value'];
                        if ($fld_val['field'] == "complete")
                            $complete = $fld_val['value'];
                        if ($fld_val['field'] == "price") {
                            $price = explode("|", $fld_val['value']);
                            $fld.=' AND (Product.products_price BETWEEN ' . $price['0'] . ' AND ' . $price['1'] . ')';
                        }
                        if (!in_array($fld_val['field'], array("color", "size", "complete", "price"))) {
                            $fld.=" AND " . $fld_val['field'] . "=" . $fld_val['value'];
                        }
                    }
                }
            }

            if ($fld == "(")
                $fld.="1=1";
            $fld.=")";

            //Fetching product list
            $prms_p = array(
                'conditions' => array(
                    $fld,
                    'OR' => array(array('Product.products_status !=' => 'Pending'),
                        array('Product.products_status !=' => 'Disapproved')),
                    'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                    ),
                    'Product.products_expiredDate >=' => date('Y-m-d H:i:s')),
                'fields' => 'Product.id'
            );
            $productid_list = $this->Product->find('list', $prms_p);

            //Fetch Product id for color
            if ($colorid) {
                $productidlist = $this->ProductAdditionalFieldValue->find('all', array('fields' => array('ProductAdditionalFieldValue.product_id'), 'conditions' => array('ProductAdditionalFieldValue.product_id' => $productid_list, 'ProductAdditionalFieldValue.values' => $colorid), 'recursive' => '-1'));
                $productid_color = Set::extract('/ProductAdditionalFieldValue/product_id', $productidlist);
            }

            //Fetch Product id for size
            if ($sizeid) {
                $this->unbindModel(array('belongsTo' => array('Sizetitle', 'Sizelabel')));
                $allsizes = $this->find('all', array('fields' => array('ProductSize.product_id'), 'conditions' => array('ProductSize.product_id' => $productid_list, 'Sizevalue.size_value' => $sizeid)));
                $productid_size = Set::extract('/ProductSize/product_id', $allsizes);
            }

            //Intersect Product ID
            if (isset($productid_color) && isset($productid_size))
                $productid_list = array_intersect($productid_list, $productid_color, $productid_size);
            elseif (isset($productid_color))
                $productid_list = array_intersect($productid_list, $productid_color);
            elseif (isset($productid_size))
                $productid_list = array_intersect($productid_list, $productid_size);

            //Fetching products information
            $flds = array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.products_views', 'Product.products_price', 'Product.products_status', 'DATEDIFF(products_expiredDate,now()) AS totaldays');
            $prms = array(
                'conditions' => array(
                    'Product.id' => $productid_list,
                    'OR' => array(
                        array('Product.products_status !=' => 'Pending'),
                        array('Product.products_status !=' => 'Disapproved')
                    ),
                    'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                    ),
                    'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                ),                
                'fields' => $flds,
                'order' => array($fild => $ord),
                'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
            );

            if ($complete == 'all') {
                $conditions = array('Cart.product_id' => $productid_list, 'Cart.order_id >' => 0, 'Cart.payment_status' => 1);
                $orders = array("Cart.add_date" => "DESC");
                $soldproductsid = $this->Cart->find('all', array("conditions" => $conditions, 'fields' => array('Cart.product_id'), 'order' => $orders, 'group' => 'Cart.product_id'));
                $soldproductsid = Set::extract('/Cart/product_id', $soldproductsid);
                $unsoldids = $this->Product->find('all', array('fields' => array('Product.id'), 'conditions' => array('Product.id' => $productid_list, 'Product.products_status' => 'Unsold', 'Product.unsold_date >' => date('Y-m-d', strtotime('-30 days')))));
                $unsoldids = Set::extract('/Product/id', $unsoldids);
                $productid_list = array_unique(array_merge($soldproductsid, $unsoldids));
                $prms = array(
                    'conditions' => array(
                        'Product.id' => $productid_list
                    ),
                    'order' => array($fild => $ord),
                    'fields' => $flds,
                    'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
                );
            } elseif ($complete == 'unsold') {
                $prms = array(
                    'conditions' => array(
                        'Product.id' => $productid_list,
                        'Product.products_status' => 'Unsold',
                        'Product.unsold_date >' => date('Y-m-d', strtotime('-30 days'))),
                    'order' => array($fild => $ord),
                    'fields' => $flds,
                    'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
                );
            } elseif ($complete == 'sold') {
                $conditions = array('Cart.product_id' => $productid_list, 'Cart.add_date >' => date('Y-m-d', strtotime('-30 days')), 'Cart.order_id >' => 0, 'Cart.payment_status' => 1);
                $orders = array("Cart.add_date" => "DESC");
                $soldproductsid = $this->Cart->find('all', array("conditions" => $conditions, 'fields' => array('Cart.product_id'), 'order' => $orders, 'group' => 'Cart.product_id'));
                $productid_list = Set::extract('/Cart/product_id', $soldproductsid);

                $prms = array(
                    'conditions' => array(
                        'Product.id' => $productid_list,
                    ),
                    'order' => array($fild => $ord),
                    'fields' => $flds,
                    'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
                );
            }

            //Fetching related category list
            $flds_cat = array('Product.category_id', 'count(Product.category_id) as total');
            $prms_cat = array(
                'conditions' => array(
                    'Product.id' => $productid_list,
                    'OR' => array(
                        array('Product.products_status !=' => 'Pending'),
                        array('Product.products_status !=' => 'Disapproved')
                    ),
                    'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                    ),
                    'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                ),
                'order' => 'total desc',
                'group' => 'Product.category_id',
                'fields' => $flds_cat
            );
            $this->Product->contain('Category.category_name');
            $cat_list = $this->Product->find('all', $prms_cat);

            //Fetching brand list
            $flds_brands = array('Product.global_brands', 'count(Product.global_brands) as totalproduct');
            $prms_brands = array(
                'conditions' => array(
                    'Product.id' => $productid_list,
                    'OR' => array(
                        array('Product.products_status !=' => 'Pending'),
                        array('Product.products_status !=' => 'Disapproved')
                    ),
                    'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                    ),
                    'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                ),
                'order' => 'totalproduct desc',
                'group' => 'Product.global_brands',
                'fields' => $flds_brands
            );
            $this->Product->contain('Brand.brand_description');
            $brands_list = $this->Product->find('all', $prms_brands);

            //Fetching condition list
            $flds_conditions = array('Product.global_conditions', 'count(Product.global_conditions) as totalproduct');
            $prms_conditions = array(
                'conditions' => array(
                    'Product.id' => $productid_list,
                    'OR' => array(
                        array('Product.products_status !=' => 'Pending'),
                        array('Product.products_status !=' => 'Disapproved')
                    ),
                    'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                    ),
                    'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                ),
                'order' => 'totalproduct desc',
                'group' => 'Product.global_conditions',
                'fields' => $flds_conditions
            );
            $this->Product->contain('ProductCondition.brand_description');
            $conditions_list = $this->Product->find('all', $prms_conditions);

            //Fetching style list
            $flds_styles = array('Product.global_styles', 'count(Product.global_styles) as totalproduct');
            $prms_styles = array(
                'conditions' => array(
                    'Product.id' => $productid_list,
                    'OR' => array(
                        array('Product.products_status !=' => 'Pending'),
                        array('Product.products_status !=' => 'Disapproved')
                    ),
                    'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                    ),
                    'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                ),
                'order' => 'totalproduct desc',
                'group' => 'Product.global_styles',
                'fields' => $flds_styles
            );
            $this->Product->contain('ProductStyle.brand_description');
            $styles_list = $this->Product->find('all', $prms_styles);

            //Fetching size list            
            $flds_sizes = array('Sizevalue.size_value');
            $prms_sizes = array(
                'conditions' => array(
                    'ProductSize.product_id' => $productid_list,
                ),
                'fields' => $flds_sizes,
                'group' => 'Sizevalue.size_value',
                'order' => 'Sizevalue.id asc'
            );
            $this->ProductSize->Behaviors->attach('Containable');
            $this->ProductSize->contain('Sizevalue');
            $sizes_list = $this->ProductSize->find('all', $prms_sizes);

            //Fetching Color list
            $color = $this->Field->find('all', array('fields' => array('Field.id'), 'conditions' => array('OR' => array(array('Field.field_name LIKE' => '%Color%'), array('Field.field_name LIKE' => '%Colour%'))), 'order' => 'Field.id  asc', 'recursive' => '-1'));
            $results = Set::extract('/Field/id', $color);
            $colors_list = $this->ProductAdditionalFieldValue->find('all', array('fields' => array('ProductAdditionalFieldValue.values', 'count(ProductAdditionalFieldValue.values) as totalproduct'), 'conditions' => array('ProductAdditionalFieldValue.values !=' => '', 'ProductAdditionalFieldValue.product_id' => $productid_list, 'ProductAdditionalFieldValue.field_id' => $results), 'order' => 'totalproduct desc', 'group' => 'ProductAdditionalFieldValue.values', 'recursive' => '-1'));

            //Set left sidbar menu
           // pr($prms);
            $this->set('products', $this->Product->find('all', $prms));
            $this->set('item', $cat_list);
            $this->set('leftmenucolor', $colors_list);
            $this->set('leftmenustyle', $styles_list);
            $this->set('leftmenucondition', $conditions_list);
            $this->set('leftmenubrand', $brands_list);
            $this->set('leftmenusize', $sizes_list);
        } else {
            $this->set('leftmenucolor', $this->Field->color_menu());
            $this->set('leftmenustyle', $this->Product->brand_menu('global_styles'));
            $this->set('leftmenucondition', $this->Product->brand_menu('global_conditions'));
            $this->set('leftmenubrand', $this->Product->brand_menu('global_brands'));
            $this->set('leftmenusize', $this->ProductSize->size_menu());
        }
    }

    function browsebysize($size=null, $sort=null, $sort2=null) {
        $this->layout = 'innerhome';
        if (isset($this->params['url']['keywords']) && $this->params['url']['keywords'] != "") {
            $query1[0]['field'] = "size";
            $query1[0]['value'] = $this->params['pass'][0];
            $query = base64_encode(serialize($query1));

            $no_push = 0;
            if (isset($this->params['url']['query']) && $this->params['url']['query'] != "") {
                $query2 = unserialize(base64_decode($this->params['url']['query']));

                $total_query2 = count($query2);
                $i = 0;
                foreach ($query2 as $query_val) {
                    if ($query_val['field'] == "size") {
                        $query2[$i]['value'] = $this->params['pass'][0];
                        $no_push = 1;
                    }
                    $i++;
                }
                 if ($no_push == 0) {
                    $query2[$i]['field'] = "size";
                    $query2[$i]['value'] = $this->params['pass'][0];
                    $no_push = 1;
                }
            }
            if ($no_push == 0) {
                $query2[0]['field'] = "size";
                $query2[0]['value'] = $this->params['pass'][0];
            }
            $query = base64_encode(serialize($query2));


            $searchkey = explode(" ", $this->params['url']['keywords']);
            $this->set('searchkey', $this->params['url']['keywords']);
            $this->set('query', $query);
            for ($i = 0; $i < count($searchkey); $i++) {
                $p_title[$i] = "Product.products_title like '%" . $searchkey[$i] . "%'";
                $p_des[$i] = "Product.products_description like '%" . $searchkey[$i] . "%'";                       
            }
        } else {
            $searchkey = '';
            $this->set('query', '');
            $this->set('searchkey', '');
        }
        $this->set('item', $this->Category->categoryArray());
        $categories = $this->Product->Category->find('list');
        $this->set(compact('categories'));
        $this->loadModel('ProductSize');
        $this->loadModel('Sizevalue');
        $productids = $this->ProductSize->size_menu1($size);
        $productids = Set::extract('/ProductSize/product_id', $productids);
        if (!empty($productids)) {
            if ($sort == 2 || $sort2 == 2) {
                $fild = 'Product.products_createDate';
                $ord = 'DESC';
            } elseif ($sort == 3 || $sort2 == 3) {
                $fild = 'Product.products_price';
                $ord = 'DESC';
            } elseif ($sort == 4 || $sort2 == 4) {
                $fild = 'Product.products_price';
                $ord = 'ASC';
            } else {
                $fild = 'Product.products_expiredDate';
                $ord = 'ASC';
            }

            $this->Product->Behaviors->attach('Containable');
            $this->Product->contain('User.username');
            $flds = array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.products_views', 'Product.products_price', 'Product.products_status', 'DATEDIFF(products_expiredDate,now()) AS totaldays');
            $prms = array(
                'conditions' => array(
                    'OR' => array(array('Product.products_status !=' => 'Pending'),
                        array('Product.products_status !=' => 'Disapproved')),
                    'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                    'Product.id' => $productids
                ),
                'order' => array($fild => $ord),
                'fields' => $flds,
                'contain' => array(
                    'User.username',
                    'Approver.username'
                )
            );

            $this->set('products', $this->Product->find('all', $prms));
        }

        if ($sort == "thumb") {
            $this->set('thumb', 'thumb');
            $this->Cookie->write('browseBySizeView', 'thumb');
        } else {
            $this->Cookie->write('browseBySizeView', 'default');
            $this->set('thumb', "");
        }
        $this->set('browseBySizeViewCookie', $this->Cookie->read('browseBySizeView'));

        $this->Sizevalue->recursive = -1;
        $this->set('size', $size);
        ///////////left-menu//////////////
        if ($searchkey) {
            $fld = "(";
            $and = 0;
            $colorid = "";
            $sizeid = "";
            $complete = "";
            if (isset($query2)) {
                foreach ($query2 as $fld_val) {
                    if ($and == 0) {
                        if ($fld_val['field'] == "color")
                            $colorid = $fld_val['value'];
                        if ($fld_val['field'] == "size")
                            $sizeid = $fld_val['value'];
                        if ($fld_val['field'] == "complete")
                            $complete = $fld_val['value'];
                        if ($fld_val['field'] == "price") {
                            $price = explode("|", $fld_val['value']);
                            $fld.='(Product.products_price BETWEEN ' . $price['0'] . ' AND ' . $price['1'] . ')';
                            $and = 1;
                        }
                        if (!in_array($fld_val['field'], array("color", "size", "complete", "price"))) {
                            $fld.=$fld_val['field'] . "=" . $fld_val['value'];
                            $and = 1;
                        }
                    } else {
                        if ($fld_val['field'] == "color")
                            $colorid = $fld_val['value'];
                        if ($fld_val['field'] == "size")
                            $sizeid = $fld_val['value'];
                        if ($fld_val['field'] == "complete")
                            $complete = $fld_val['value'];
                        if ($fld_val['field'] == "price") {
                            $price = explode("|", $fld_val['value']);
                            $fld.=' AND (Product.products_price BETWEEN ' . $price['0'] . ' AND ' . $price['1'] . ')';
                        }
                        if (!in_array($fld_val['field'], array("color", "size", "complete", "price"))) {
                            $fld.=" AND " . $fld_val['field'] . "=" . $fld_val['value'];
                        }
                    }
                }
            }

            if ($fld == "(")
                $fld.="1=1";
            $fld.=")";

            //Fetching product list
            $prms_p = array(
                'conditions' => array(
                    $fld,
                    'OR' => array(array('Product.products_status !=' => 'Pending'),
                        array('Product.products_status !=' => 'Disapproved')),
                    'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                    ),
                    'Product.products_expiredDate >=' => date('Y-m-d H:i:s')),
                'fields' => 'Product.id'
            );
            $productid_list = $this->Product->find('list', $prms_p);

            //Fetch Product id for color
            if ($colorid) {
                $productidlist = $this->ProductAdditionalFieldValue->find('all', array('fields' => array('ProductAdditionalFieldValue.product_id'), 'conditions' => array('ProductAdditionalFieldValue.product_id' => $productid_list, 'ProductAdditionalFieldValue.values' => $colorid), 'recursive' => '-1'));
                $productid_color = Set::extract('/ProductAdditionalFieldValue/product_id', $productidlist);
            }

            //Fetch Product id for size
            if ($sizeid) {
                $this->ProductSize->unbindModel(array('belongsTo' => array('Sizetitle', 'Sizelabel')));
                $allsizes = $this->ProductSize->find('all', array('fields' => array('ProductSize.product_id'), 'conditions' => array('ProductSize.product_id' => $productid_list, 'Sizevalue.size_value' => $sizeid)));
                $productid_size = Set::extract('/ProductSize/product_id', $allsizes);
            }

            //Intersect Product ID
            if (isset($productid_color) && isset($productid_size))
                $productid_list = array_intersect($productid_list, $productid_color, $productid_size);
            elseif (isset($productid_color))
                $productid_list = array_intersect($productid_list, $productid_color);
            elseif (isset($productid_size))
                $productid_list = array_intersect($productid_list, $productid_size);

            //Fetching products information
            $flds = array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.products_views', 'Product.products_price', 'Product.products_status', 'DATEDIFF(products_expiredDate,now()) AS totaldays');
            $prms = array(
                'conditions' => array(
                    'Product.id' => $productid_list,
                    'OR' => array(array('Product.products_status !=' => 'Pending'),
                        array('Product.products_status !=' => 'Disapproved')),
                    'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                    ),
                    'Product.products_expiredDate >=' => date('Y-m-d H:i:s')),
                'fields' => $flds,
                'order' => array($fild => $ord),
                'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
            );

            if ($complete == 'all') {
                $conditions = array('Cart.product_id' => $productid_list, 'Cart.order_id >' => 0, 'Cart.payment_status' => 1);
                $orders = array("Cart.add_date" => "DESC");
                $soldproductsid = $this->Cart->find('all', array("conditions" => $conditions, 'fields' => array('Cart.product_id'), 'order' => $orders, 'group' => 'Cart.product_id'));
                $soldproductsid = Set::extract('/Cart/product_id', $soldproductsid);
                $unsoldids = $this->Product->find('all', array('fields' => array('Product.id'), 'conditions' => array('Product.id' => $productid_list, 'Product.products_status' => 'Unsold', 'Product.unsold_date >' => date('Y-m-d', strtotime('-30 days')))));
                $unsoldids = Set::extract('/Product/id', $unsoldids);
                $productid_list = array_unique(array_merge($soldproductsid, $unsoldids));
                $prms = array(
                    'conditions' => array(
                        'Product.id' => $productid_list
                    ),
                    'order' => array($fild => $ord),
                    'fields' => $flds,
                    'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
                );
            } elseif ($complete == 'unsold') {
                $prms = array(
                    'conditions' => array(
                        'Product.id' => $productid_list,
                        'Product.products_status' => 'Unsold',
                        'Product.unsold_date >' => date('Y-m-d', strtotime('-30 days'))),
                    'order' => array($fild => $ord),
                    'fields' => $flds,
                    'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
                );
            } elseif ($complete == 'sold') {
                $conditions = array('Cart.product_id' => $productid_list, 'Cart.add_date >' => date('Y-m-d', strtotime('-30 days')), 'Cart.order_id >' => 0, 'Cart.payment_status' => 1);
                $orders = array("Cart.add_date" => "DESC");
                $soldproductsid = $this->Cart->find('all', array("conditions" => $conditions, 'fields' => array('Cart.product_id'), 'order' => $orders, 'group' => 'Cart.product_id'));
                $productid_list = Set::extract('/Cart/product_id', $soldproductsid);

                $prms = array(
                    'conditions' => array(
                        'Product.id' => $productid_list,
                    ),
                    'order' => array($fild => $ord),
                    'fields' => $flds,
                    'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
                );
            }

            //Fetching related category list
            $flds_cat = array('Product.category_id', 'count(Product.category_id) as total');
            $prms_cat = array(
                'conditions' => array(
                    'Product.id' => $productid_list,
                    'OR' => array(
                        array('Product.products_status !=' => 'Pending'),
                        array('Product.products_status !=' => 'Disapproved')
                    ),
                    'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                    ),
                    'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                ),
                'order' => 'total desc',
                'group' => 'Product.category_id',
                'fields' => $flds_cat
            );
            $this->Product->contain('Category.category_name');
            $cat_list = $this->Product->find('all', $prms_cat);

            //Fetching brand list
            $flds_brands = array('Product.global_brands', 'count(Product.global_brands) as totalproduct');
            $prms_brands = array(
                'conditions' => array(
                    'Product.id' => $productid_list,
                    'OR' => array(
                        array('Product.products_status !=' => 'Pending'),
                        array('Product.products_status !=' => 'Disapproved')
                    ),
                    'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                    ),
                    'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                ),
                'order' => 'totalproduct desc',
                'group' => 'Product.global_brands',
                'fields' => $flds_brands
            );
            $this->Product->contain('Brand.brand_description');
            $brands_list = $this->Product->find('all', $prms_brands);

            //Fetching condition list
            $flds_conditions = array('Product.global_conditions', 'count(Product.global_conditions) as totalproduct');
            $prms_conditions = array(
                'conditions' => array(
                    'Product.id' => $productid_list,
                    'OR' => array(
                        array('Product.products_status !=' => 'Pending'),
                        array('Product.products_status !=' => 'Disapproved')
                    ),
                    'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                    ),
                    'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                ),
                'order' => 'totalproduct desc',
                'group' => 'Product.global_conditions',
                'fields' => $flds_conditions
            );
            $this->Product->contain('ProductCondition.brand_description');
            $conditions_list = $this->Product->find('all', $prms_conditions);

            //Fetching style list
            $flds_styles = array('Product.global_styles', 'count(Product.global_styles) as totalproduct');
            $prms_styles = array(
                'conditions' => array(
                    'Product.id' => $productid_list,
                    'OR' => array(
                        array('Product.products_status !=' => 'Pending'),
                        array('Product.products_status !=' => 'Disapproved')
                    ),
                    'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                    ),
                    'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                ),
                'order' => 'totalproduct desc',
                'group' => 'Product.global_styles',
                'fields' => $flds_styles
            );
            $this->Product->contain('ProductStyle.brand_description');
            $styles_list = $this->Product->find('all', $prms_styles);

            //Fetching size list            
            $flds_sizes = array('Sizevalue.size_value');
            $prms_sizes = array(
                'conditions' => array(
                    'ProductSize.product_id' => $productid_list,
                ),
                'fields' => $flds_sizes,
                'group' => 'Sizevalue.size_value',
                'order' => 'Sizevalue.id asc'
            );
            $this->ProductSize->Behaviors->attach('Containable');
            $this->ProductSize->contain('Sizevalue');
            $sizes_list = $this->ProductSize->find('all', $prms_sizes);

            //Fetching Color list
            $color = $this->Field->find('all', array('fields' => array('Field.id'), 'conditions' => array('OR' => array(array('Field.field_name LIKE' => '%Color%'), array('Field.field_name LIKE' => '%Colour%'))), 'order' => 'Field.id  asc', 'recursive' => '-1'));
            $results = Set::extract('/Field/id', $color);
            $colors_list = $this->ProductAdditionalFieldValue->find('all', array('fields' => array('ProductAdditionalFieldValue.values', 'count(ProductAdditionalFieldValue.values) as totalproduct'), 'conditions' => array('ProductAdditionalFieldValue.values !=' => '', 'ProductAdditionalFieldValue.product_id' => $productid_list, 'ProductAdditionalFieldValue.field_id' => $results), 'order' => 'totalproduct desc', 'group' => 'ProductAdditionalFieldValue.values', 'recursive' => '-1'));

            //Set left sidbar menu

            $this->set('products', $this->Product->find('all', $prms));
            $this->set('item', $cat_list);
            $this->set('leftmenucolor', $colors_list);
            $this->set('leftmenustyle', $styles_list);
            $this->set('leftmenucondition', $conditions_list);
            $this->set('leftmenubrand', $brands_list);
            $this->set('leftmenusize', $sizes_list);
        } else {
            $this->set('leftmenucolor', $this->Field->color_menu());
            $this->set('leftmenustyle', $this->Product->brand_menu('global_styles'));
            $this->set('leftmenucondition', $this->Product->brand_menu('global_conditions'));
            $this->set('leftmenubrand', $this->Product->brand_menu('global_brands'));
            $this->set('leftmenusize', $this->ProductSize->size_menu());
        }
    }

    function browsebycolor($colorid=null, $sort=null, $sort2=null) {
        $this->layout = 'innerhome';

        if (isset($this->params['url']['keywords']) && $this->params['url']['keywords'] != "") {
            $query1[0]['field'] = "color";
            $query1[0]['value'] = $this->params['pass'][0];
            $query = base64_encode(serialize($query1));

            $no_push = 0;
            if (isset($this->params['url']['query']) && $this->params['url']['query'] != "") {
                $query2 = unserialize(base64_decode($this->params['url']['query']));
                $total_query2 = count($query2);
                $i = 0;
                foreach ($query2 as $query_val) {
                    if ($query_val['field'] == "color") {
                        $query2[$i]['value'] = $this->params['pass'][0];
                        $no_push = 1;
                    }
                    $i++;
                }
                 if ($no_push == 0) {
                    $query2[$i]['field'] = "color";
                    $query2[$i]['value'] = $this->params['pass'][0];
                    $no_push = 1;
                }
            }
            if ($no_push == 0) {
                $query2[0]['field'] = "color";
                $query2[0]['value'] = $this->params['pass'][0];
            }
            $query = base64_encode(serialize($query2));

            $searchkey = explode(" ", $this->params['url']['keywords']);
            $this->set('searchkey', $this->params['url']['keywords']);
            $this->set('query', $query);
            for ($i = 0; $i < count($searchkey); $i++) {
                $p_title[$i] = "Product.products_title like '%" . $searchkey[$i] . "%'";
                $p_des[$i] = "Product.products_description like '%" . $searchkey[$i] . "%'";                       
            }
        } else {
            $searchkey = '';
            $this->set('query', '');
            $this->set('searchkey', '');
        }

        $this->set('item', $this->Category->categoryArray());
        $categories = $this->Product->Category->find('list');
        $this->set(compact('categories'));
        $this->Product->Behaviors->attach('Containable');
        $this->Product->contain('User.username');
        $flds = array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.products_views', 'Product.products_price', 'Product.products_status', 'DATEDIFF(products_expiredDate,now()) AS totaldays');

        if ($sort == 2 || $sort2 == 2) {
            $fild = 'Product.products_createDate';
            $ord = 'DESC';
        } elseif ($sort == 3 || $sort2 == 3) {
            $fild = 'Product.products_price';
            $ord = 'DESC';
        } elseif ($sort == 4 || $sort2 == 4) {
            $fild = 'Product.products_price';
            $ord = 'ASC';
        } else {
            $fild = 'Product.products_expiredDate';
            $ord = 'ASC';
        }


        $productidlist = $this->ProductAdditionalFieldValue->find('all', array('fields' => array('ProductAdditionalFieldValue.product_id'), 'conditions' => array('ProductAdditionalFieldValue.values' => $colorid), 'recursive' => '-1'));
        $productid_list = Set::extract('/ProductAdditionalFieldValue/product_id', $productidlist);

        $prms = array(
            'conditions' => array(
                'Product.id' => $productid_list,
                'OR' => array(array('Product.products_status !=' => 'Pending'),
                    array('Product.products_status !=' => 'Disapproved')),
                'Product.products_expiredDate >=' => date('Y-m-d H:i:s')),
            'order' => array($fild => $ord),
            'fields' => $flds,
            'contain' => array(
                'User.username',
                'Approver.username'
            )
        );
        if ($sort == "thumb") {
            $this->set('thumb', 'thumb');
            $this->Cookie->write('browseByColorView', 'thumb');
        } else {
            $this->Cookie->write('browseByColorView', 'default');
            $this->set('thumb', "");
        }
        $this->set('browseByColorViewCookie', $this->Cookie->read('browseByColorView'));

        $this->set('products', $this->Product->find('all', $prms));
        $this->set('colorid', $colorid);
        ///////////left-menu//////////////
        if ($searchkey) {
            $fld = "(";
            $and = 0;
            $colorid = "";
            $sizeid = "";
            $complete = "";
            if (isset($query2)) {
                foreach ($query2 as $fld_val) {
                    if ($and == 0) {
                        if ($fld_val['field'] == "color")
                            $colorid = $fld_val['value'];
                        if ($fld_val['field'] == "size")
                            $sizeid = $fld_val['value'];
                        if ($fld_val['field'] == "complete")
                            $complete = $fld_val['value'];
                        if ($fld_val['field'] == "price") {
                            $price = explode("|", $fld_val['value']);
                            $fld.='(Product.products_price BETWEEN ' . $price['0'] . ' AND ' . $price['1'] . ')';
                            $and = 1;
                        }
                        if (!in_array($fld_val['field'], array("color", "size", "complete", "price"))) {
                            $fld.=$fld_val['field'] . "=" . $fld_val['value'];
                            $and = 1;
                        }
                    } else {
                        if ($fld_val['field'] == "color")
                            $colorid = $fld_val['value'];
                        if ($fld_val['field'] == "size")
                            $sizeid = $fld_val['value'];
                        if ($fld_val['field'] == "complete")
                            $complete = $fld_val['value'];
                        if ($fld_val['field'] == "price") {
                            $price = explode("|", $fld_val['value']);
                            $fld.=' AND (Product.products_price BETWEEN ' . $price['0'] . ' AND ' . $price['1'] . ')';
                        }
                        if (!in_array($fld_val['field'], array("color", "size", "complete", "price"))) {
                            $fld.=" AND " . $fld_val['field'] . "=" . $fld_val['value'];
                        }
                    }
                }
            }

            if ($fld == "(")
                $fld.="1=1";
            $fld.=")";

            //Fetching product list
            $prms_p = array(
                'conditions' => array(
                    $fld,
                    'OR' => array(array('Product.products_status !=' => 'Pending'),
                        array('Product.products_status !=' => 'Disapproved')),
                    'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                    ),
                    'Product.products_expiredDate >=' => date('Y-m-d H:i:s')),
                'fields' => 'Product.id'
            );
            $productid_list = $this->Product->find('list', $prms_p);

            //Fetch Product id for color
            if ($colorid) {
                $productidlist = $this->ProductAdditionalFieldValue->find('all', array('fields' => array('ProductAdditionalFieldValue.product_id'), 'conditions' => array('ProductAdditionalFieldValue.product_id' => $productid_list, 'ProductAdditionalFieldValue.values' => $colorid), 'recursive' => '-1'));
                $productid_color = Set::extract('/ProductAdditionalFieldValue/product_id', $productidlist);
            }

            //Fetch Product id for size
            if ($sizeid) {
                $this->unbindModel(array('belongsTo' => array('Sizetitle', 'Sizelabel')));
                $allsizes = $this->find('all', array('fields' => array('ProductSize.product_id'), 'conditions' => array('ProductSize.product_id' => $productid_list, 'Sizevalue.size_value' => $sizeid)));
                $productid_size = Set::extract('/ProductSize/product_id', $allsizes);
            }

            //Intersect Product ID
            if (isset($productid_color) && isset($productid_size))
                $productid_list = array_intersect($productid_list, $productid_color, $productid_size);
            elseif (isset($productid_color))
                $productid_list = array_intersect($productid_list, $productid_color);
            elseif (isset($productid_size))
                $productid_list = array_intersect($productid_list, $productid_size);

            //Fetching products information
            $flds = array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.products_views', 'Product.products_price', 'Product.products_status', 'DATEDIFF(products_expiredDate,now()) AS totaldays');
            $prms = array(
                'conditions' => array(
                    'Product.id' => $productid_list,
                    'OR' => array(array('Product.products_status !=' => 'Pending'),
                        array('Product.products_status !=' => 'Disapproved')),
                    'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                    ),
                    'Product.products_expiredDate >=' => date('Y-m-d H:i:s')),
                'order' => array($fild => $ord),
                'fields' => $flds,
                'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
            );

            if ($complete == 'all') {
                $conditions = array('Cart.product_id' => $productid_list, 'Cart.order_id >' => 0, 'Cart.payment_status' => 1);
                $orders = array("Cart.add_date" => "DESC");
                $soldproductsid = $this->Cart->find('all', array("conditions" => $conditions, 'fields' => array('Cart.product_id'), 'order' => $orders, 'group' => 'Cart.product_id'));
                $soldproductsid = Set::extract('/Cart/product_id', $soldproductsid);
                $unsoldids = $this->Product->find('all', array('fields' => array('Product.id'), 'conditions' => array('Product.id' => $productid_list, 'Product.products_status' => 'Unsold', 'Product.unsold_date >' => date('Y-m-d', strtotime('-30 days')))));
                $unsoldids = Set::extract('/Product/id', $unsoldids);
                $productid_list = array_unique(array_merge($soldproductsid, $unsoldids));
                $prms = array(
                    'conditions' => array(
                        'Product.id' => $productid_list
                    ),
                    'order' => array($fild => $ord),
                    'fields' => $flds,
                    'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
                );
            } elseif ($complete == 'unsold') {
                $prms = array(
                    'conditions' => array(
                        'Product.id' => $productid_list,
                        'Product.products_status' => 'Unsold',
                        'Product.unsold_date >' => date('Y-m-d', strtotime('-30 days'))),
                    'order' => array($fild => $ord),
                    'fields' => $flds,
                    'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
                );
            } elseif ($complete == 'sold') {
                $conditions = array('Cart.product_id' => $productid_list, 'Cart.add_date >' => date('Y-m-d', strtotime('-30 days')), 'Cart.order_id >' => 0, 'Cart.payment_status' => 1);
                $orders = array("Cart.add_date" => "DESC");
                $soldproductsid = $this->Cart->find('all', array("conditions" => $conditions, 'fields' => array('Cart.product_id'), 'order' => $orders, 'group' => 'Cart.product_id'));
                $productid_list = Set::extract('/Cart/product_id', $soldproductsid);

                $prms = array(
                    'conditions' => array(
                        'Product.id' => $productid_list,
                    ),
                    'order' => array($fild => $ord),
                    'fields' => $flds,
                    'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
                );
            }

            //Fetching related category list
            $flds_cat = array('Product.category_id', 'count(Product.category_id) as total');
            $prms_cat = array(
                'conditions' => array(
                    'Product.id' => $productid_list,
                    'OR' => array(
                        array('Product.products_status !=' => 'Pending'),
                        array('Product.products_status !=' => 'Disapproved')
                    ),
                    'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                    ),
                    'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                ),
                'order' => 'total desc',
                'group' => 'Product.category_id',
                'fields' => $flds_cat
            );
            $this->Product->contain('Category.category_name');
            $cat_list = $this->Product->find('all', $prms_cat);

            //Fetching brand list
            $flds_brands = array('Product.global_brands', 'count(Product.global_brands) as totalproduct');
            $prms_brands = array(
                'conditions' => array(
                    'Product.id' => $productid_list,
                    'OR' => array(
                        array('Product.products_status !=' => 'Pending'),
                        array('Product.products_status !=' => 'Disapproved')
                    ),
                    'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                    ),
                    'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                ),
                'order' => 'totalproduct desc',
                'group' => 'Product.global_brands',
                'fields' => $flds_brands
            );
            $this->Product->contain('Brand.brand_description');
            $brands_list = $this->Product->find('all', $prms_brands);

            //Fetching condition list
            $flds_conditions = array('Product.global_conditions', 'count(Product.global_conditions) as totalproduct');
            $prms_conditions = array(
                'conditions' => array(
                    'Product.id' => $productid_list,
                    'OR' => array(
                        array('Product.products_status !=' => 'Pending'),
                        array('Product.products_status !=' => 'Disapproved')
                    ),
                    'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                    ),
                    'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                ),
                'order' => 'totalproduct desc',
                'group' => 'Product.global_conditions',
                'fields' => $flds_conditions
            );
            $this->Product->contain('ProductCondition.brand_description');
            $conditions_list = $this->Product->find('all', $prms_conditions);

            //Fetching style list
            $flds_styles = array('Product.global_styles', 'count(Product.global_styles) as totalproduct');
            $prms_styles = array(
                'conditions' => array(
                    'Product.id' => $productid_list,
                    'OR' => array(
                        array('Product.products_status !=' => 'Pending'),
                        array('Product.products_status !=' => 'Disapproved')
                    ),
                    'AND' => array(
                                'OR'=>array(
                                    array(
                                    'OR' => $p_title
                                    ),
                                array(
                                    'OR' => $p_des
                                    )
                                )
                    ),
                    'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                ),
                'order' => 'totalproduct desc',
                'group' => 'Product.global_styles',
                'fields' => $flds_styles
            );
            $this->Product->contain('ProductStyle.brand_description');
            $styles_list = $this->Product->find('all', $prms_styles);

            //Fetching size list            
            $flds_sizes = array('Sizevalue.size_value');
            $prms_sizes = array(
                'conditions' => array(
                    'ProductSize.product_id' => $productid_list,
                ),
                'fields' => $flds_sizes,
                'group' => 'Sizevalue.size_value',
                'order' => 'Sizevalue.id asc'
            );
            $this->ProductSize->Behaviors->attach('Containable');
            $this->ProductSize->contain('Sizevalue');
            $sizes_list = $this->ProductSize->find('all', $prms_sizes);

            //Fetching Color list
            $color = $this->Field->find('all', array('fields' => array('Field.id'), 'conditions' => array('OR' => array(array('Field.field_name LIKE' => '%Color%'), array('Field.field_name LIKE' => '%Colour%'))), 'order' => 'Field.id  asc', 'recursive' => '-1'));
            $results = Set::extract('/Field/id', $color);
            $colors_list = $this->ProductAdditionalFieldValue->find('all', array('fields' => array('ProductAdditionalFieldValue.values', 'count(ProductAdditionalFieldValue.values) as totalproduct'), 'conditions' => array('ProductAdditionalFieldValue.values !=' => '', 'ProductAdditionalFieldValue.product_id' => $productid_list, 'ProductAdditionalFieldValue.field_id' => $results), 'order' => 'totalproduct desc', 'group' => 'ProductAdditionalFieldValue.values', 'recursive' => '-1'));

            //Set left sidbar menu
            
            $this->set('products', $this->Product->find('all', $prms));
            $this->set('item', $cat_list);
            $this->set('leftmenucolor', $colors_list);
            $this->set('leftmenustyle', $styles_list);
            $this->set('leftmenucondition', $conditions_list);
            $this->set('leftmenubrand', $brands_list);
            $this->set('leftmenusize', $sizes_list);
        } else {
            $this->set('leftmenucolor', $this->Field->color_menu());
            $this->set('leftmenustyle', $this->Product->brand_menu('global_styles'));
            $this->set('leftmenucondition', $this->Product->brand_menu('global_conditions'));
            $this->set('leftmenubrand', $this->Product->brand_menu('global_brands'));
            $this->set('leftmenusize', $this->ProductSize->size_menu());
        }
    }

    function getnamebyid($id=null) {
        $this->layout = null;
        $this->autoRender = false;
        $this->Category->recursive = -1;
        return $this->Category->findById($id, array('fields' => 'Category.category_name'));
    }

    function brandnamebyid($id=null) {
        $this->layout = null;
        $this->autoRender = false;
        $this->Brand->recursive = -1;
        return $this->Brand->findById($id, array('fields' => 'Brand.brand_description'));
    }

    function report_problem($id=null) {
        if (!empty($this->data)) {
            /////////////messages center/////////
            $this->loadModel('Message');
            $this->loadModel('MessageTrack');
            $this->data['Message']['subject'] = $this->data['Reporteditem']['subject'];
            $this->data['Message']['message'] = $this->data['Reporteditem']['description'];
            $this->Message->create();
            if ($this->Message->save($this->data)) {
                $mid = $this->Message->getLastInsertID();
                /////////for sent item//////
                $this->data['MessageTrack']['id'] = null;
                $this->data['MessageTrack']['message_id'] = $mid;
                $this->data['MessageTrack']['to_id'] = 1;
                $this->data['MessageTrack']['from_id'] = $this->Auth->user('id');
                $this->data['MessageTrack']['msg_type'] = 0;
                $this->data['MessageTrack']['read'] = 0;
                $this->data['MessageTrack']['star'] = 0;
                $this->data['MessageTrack']['reply'] = 0;
                $this->MessageTrack->save($this->data);
                ///////////for inbox///////
                $this->data['MessageTrack']['id'] = null;
                $this->data['MessageTrack']['message_id'] = $mid;
                $this->data['MessageTrack']['to_id'] = 1;
                $this->data['MessageTrack']['from_id'] = $this->Auth->user('id');
                $this->data['MessageTrack']['msg_type'] = 1;
                $this->data['MessageTrack']['read'] = 0;
                $this->data['MessageTrack']['star'] = 0;
                $this->data['MessageTrack']['reply'] = 0;
                $this->MessageTrack->save($this->data);
            }
            ////////////////////////////////
            $this->loadModel('Reporteditem');
            $this->Reporteditem->save($this->data['Reporteditem']);
        }
        $this->ask_a_question($id);
    }

    function backstage_reported_items() {
        $this->layout = 'admin';
        $this->loadModel('Reporteditem');
        $this->Reporteditem->Behaviors->attach('Containable');
        $this->paginate = array('limit' => 25,
            'order' => array('Reporteditem.id' => 'desc'),
            'contain' => array(
                'Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.User.username', 'Reporter.username'
            )
        );
        $this->set('products', $this->paginate('Reporteditem'));
    }

    function backstage_salesreview() {
        $this->layout = 'adminsales';
        $this->loadModel('Order');
        $this->Order->Behaviors->attach('Containable');
        $this->Order->bindModel(
                array('belongsTo' => array(
                        'Seller' => array(
                            'className' => 'User',
                            'foreignKey' => 'seller_id'
                        ),
                        'Product' => array(
                            'className' => 'Product',
                            'foreignKey' => 'product_id'
                        ),
                        'User' => array(
                            'className' => 'User',
                            'foreignKey' => 'user_id'
                        )
                    )
                )
        );
        if (!empty($_POST)) {
            $reports = $this->Order->find('all', array('fields' => array('Order.id', 'Order.quantity', 'Order.product_cost', 'Order.user_id', 'Order.add_date'),
                'contain' => array(
                    'Product.id', 'Product.products_title', 'User.username', 'Seller.username'
                ),
                'conditions' => array('Order.add_date BETWEEN ? AND ?' =>
                    array(date('Y-m-d', strtotime($_POST['start'])), date('Y-m-d', strtotime($_POST['end'])))),
                'order' => 'Order.id asc'));
            $this->set('reports', $reports);
            $totalproduct = $this->Order->find('all', array('fields' =>
                array('Order.id', 'sum(Order.quantity) as tquantity'),
                'conditions' => array('Order.add_date BETWEEN ? AND ?' =>
                    array(date('Y-m-d', strtotime($_POST['start'])), date('Y-m-d', strtotime($_POST['end']))))));
            $this->set('totalproduct', $totalproduct);
            $totalbuyers = $this->Order->find('all', array('fields' => array('Order.id', 'count(DISTINCT Order.user_id) as totalbuyer'),
                'conditions' => array('Order.add_date BETWEEN ? AND ?' =>
                    array(date('Y-m-d', strtotime($_POST['start'])), date('Y-m-d', strtotime($_POST['end']))))));
            $this->set('totalbuyers', $totalbuyers);
            $totalseller = $this->Order->find('all', array('fields' => array('Order.id', 'count(DISTINCT Order.seller_id) as totalseller'),
                'conditions' => array('Order.add_date BETWEEN ? AND ?' =>
                    array(date('Y-m-d', strtotime($_POST['start'])), date('Y-m-d', strtotime($_POST['end']))))));
            $this->set('totalseller', $totalseller);
            $totalsales = $this->Order->find('all', array('fields' => array('Order.id', 'sum(Order.quantity * Order.product_cost) as totalsale'),
                'conditions' => array('Order.add_date BETWEEN ? AND ?' =>
                    array(date('Y-m-d', strtotime($_POST['start'])), date('Y-m-d', strtotime($_POST['end']))))));
            $this->set('totalsales', $totalsales);
            $this->set('startdate', $_POST['start']);
            $this->set('enddate', $_POST['end']);
        } else {
            $reports = null;
            $this->set('reports', $reports);
        }
    }

    function contact_seller($id) {
        $this->ask_a_question($id);
    }

    function store($id) {
        $this->layout = 'innerhome';
        //left navigation
        $this->set('item', $this->Category->categoryArray());
        $this->Product->Behaviors->attach('Containable');
        $this->Product->contain('Category');
        $allProducts = $this->Product->find('all', array('conditions' => array('OR' => array(array('Product.products_status' => 'Active'), array('Product.products_status' => 'Approved')), 'Product.products_expiredDate >=' => date("Y-m-d H:i:s"), 'Product.user_id' => $id)));
        $this->set('sellerProducts', $this->Product->store($allProducts));
    }

    function negotiate($pid=null, $flag=null) {
        $this->layout = false;
        $this->set('pid', $pid);
        $this->loadModel('Negotiation');
        if (!empty($this->data)) {
            $this->Product->recursive = -1;
            $productinfo = $this->Product->findById($this->data['Negotiation']['product_id'], array('Product.id', 'Product.products_offerAcceptLeastPrice', 'Product.products_offerDeclineLowerPrice'));
            if (($productinfo['Product']['products_offerAcceptLeastPrice'] > 0) AND ($productinfo['Product']['products_offerAcceptLeastPrice'] <= $this->data['Negotiation']['last_offer'])) {
                $this->data['Negotiation']['status'] = 'Accepted';
            } elseif ($productinfo['Product']['products_offerDeclineLowerPrice'] > $this->data['Negotiation']['last_offer']) {
                $this->data['Negotiation']['status'] = 'Rejected';
            } else {
                $this->data['Negotiation']['status'] = 'Pending';
            }
            $this->data['Negotiation']['buyer_id'] = $this->Auth->user('id');
            $this->Negotiation->save($this->data['Negotiation']);
            $this->render('negotiate_status1');
        }
        if ($flag == null) {
            $limitchk = $this->Negotiation->find('count', array('conditions' => array('Negotiation.buyer_id' => $this->Auth->user('id'), 'Negotiation.product_id' => $pid)));
            if ($limitchk >= 3) {
                $this->render('negotiate_limit');
            } else {

                $statuschk = $this->Negotiation->find('first', array('conditions' => array('Negotiation.buyer_id' => $this->Auth->user('id'), 'Negotiation.product_id' => $pid),
                    'order' => array('Negotiation.id DESC'), 'recursive' => -1));
                if ($statuschk['Negotiation']['status'] == 'Pending') {
                    $this->render('negotiate_status1');
                } elseif ($statuschk['Negotiation']['status'] == 'Rejected') {
                    $this->render('negotiate_status');
                } elseif ($statuschk['Negotiation']['status'] == 'Accepted') {
                    $this->render('negotiate_status2');
                }
            }
        }
        $limitchk = $this->Negotiation->find('count', array('conditions' => array('Negotiation.buyer_id' => $this->Auth->user('id'), 'Negotiation.product_id' => $pid)));
        if ($limitchk >= 3) {
            $this->render('negotiate_limit');
        }
        $history = $this->Negotiation->find('all', array('conditions' => array('Negotiation.buyer_id' => $this->Auth->user('id'), 'Negotiation.product_id' => $pid), 'recursive' => -1));
        $this->set('history', $history);
        $this->Product->Behaviors->attach('Containable');
        $this->Product->contain('User.username');
        $productinfo = $this->Product->findById($pid, array('Product.id', 'Product.products_offerDeclineLowerPrice'));
        $this->set('productinfo', $productinfo);
        if ($flag == 2) {
            $pendinginfo = $this->Negotiation->find('first', array('conditions' => array('Negotiation.buyer_id' => $this->Auth->user('id'), 'Negotiation.product_id' => $pid, 'Negotiation.status' => 'Pending'),
                'order' => array('Negotiation.id DESC'), 'recursive' => -1));
            $this->set('pendinginfo', $pendinginfo);
        }
        $this->set('flag', $flag);
    }

    function negotiation_accepted() {
        $this->loadModel('Negotiation');
        if ($this->Session->read('grouptype') == 'Buyers') {
            $this->paginate = array('limit' => 25,
                'conditions' => array(
                    'Negotiation.status' => 'Accepted', 'Negotiation.buyer_id' => $this->Auth->user('id')),
                'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.products_price', 'Negotiation.last_offer', 'Negotiation.cart_chk', 'User.username')
            );
        } elseif ($this->Session->read('grouptype') == 'Sellers') {
            $this->paginate = array('limit' => 25,
                'conditions' => array(
                    'Negotiation.status' => 'Accepted', 'Negotiation.seller_id' => $this->Auth->user('id')),
                'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.products_price', 'Negotiation.id', 'Negotiation.last_offer', 'Negotiation.buyer_id', 'Negotiation.cart_chk', 'Buyer.username')
            );
        }
        $this->set('products', $this->paginate('Negotiation'));
        $this->layout = "innerhome";
    }

    function negotiation_pending() {
        $this->loadModel('Negotiation');
        if ($this->Session->read('grouptype') == 'Buyers') {
            $this->paginate = array('limit' => 25,
                'conditions' => array(
                    'Negotiation.status' => 'Pending', 'Negotiation.buyer_id' => $this->Auth->user('id')),
                'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.products_price', 'Negotiation.last_offer', 'Negotiation.cart_chk', 'User.username')
            );
        } elseif ($this->Session->read('grouptype') == 'Sellers') {
            $this->paginate = array('limit' => 25,
                'conditions' => array(
                    'Negotiation.status' => 'Pending', 'Negotiation.seller_id' => $this->Auth->user('id')),
                'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.products_price', 'Negotiation.id', 'Negotiation.last_offer', 'Negotiation.buyer_id', 'Negotiation.cart_chk', 'Buyer.username')
            );
        }
        $this->set('products', $this->paginate('Negotiation'));
        $this->layout = "innerhome";
    }

    function negotiation_rejected() {
        $this->loadModel('Negotiation');
        if ($this->Session->read('grouptype') == 'Buyers') {
            $this->paginate = array('limit' => 25,
                'conditions' => array(
                    'Negotiation.status' => 'Rejected', 'Negotiation.buyer_id' => $this->Auth->user('id')),
                'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.products_price', 'Negotiation.last_offer', 'Negotiation.cart_chk', 'Negotiation.id', 'User.username'),
                'order' => array(
                    'Negotiation.id' => 'desc'
                )
            );
        } elseif ($this->Session->read('grouptype') == 'Sellers') {
            $this->paginate = array('limit' => 25,
                'conditions' => array(
                    'Negotiation.status' => 'Rejected', 'Negotiation.seller_id' => $this->Auth->user('id')),
                'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.products_price', 'Negotiation.id', 'Negotiation.last_offer', 'Negotiation.buyer_id', 'Negotiation.cart_chk', 'Buyer.username')
            );
        }

        $this->set('products', $this->paginate('Negotiation'));
        $this->layout = "innerhome";
    }

    function getnegotiation($pid=null, $bid=null) {
        $this->loadModel('Negotiation');
        if ($bid == null) {
            return $this->Negotiation->find('all', array('conditions' => array('Negotiation.buyer_id' => $this->Auth->user('id'), 'Negotiation.product_id' => $pid), 'recursive' => -1));
        } else {
            return $this->Negotiation->find('all', array('conditions' => array('Negotiation.buyer_id' => $bid, 'Negotiation.seller_id' => $this->Auth->user('id'), 'Negotiation.product_id' => $pid), 'recursive' => -1));
        }
    }

    function delete_negotiation($pid=null) {
        $this->autoRender = false;
        $this->layout = false;
        $this->loadModel('Negotiation');
        $conditions = array('Negotiation.buyer_id' => $this->Auth->user('id'), 'Negotiation.product_id' => $pid);
        $this->Negotiation->deleteAll($conditions);
    }

    function reject_negotiate($nid=null) {
        $this->layout = false;
        if (!empty($this->data)) {
            $this->loadModel('Negotiation');
            $this->data['Negotiation']['status'] = 'Rejected';
            $this->Negotiation->save($this->data['Negotiation']);
            $this->render('reject_msg');
        }
        $this->set('nid', $nid);
    }

    function accept_negotiate($nid=null) {
        $this->layout = false;
        if (!empty($this->data)) {
            $this->loadModel('Negotiation');
            $this->data['Negotiation']['status'] = 'Accepted';
            $this->Negotiation->save($this->data['Negotiation']);
            $this->render('reject_msg1');
        }
        $this->set('nid', $nid);
    }

    function sold() {
        $this->Product->recursive = -1;
        $seller_products = $this->Product->find("list", array('conditions' => array("Product.user_id" => $this->Auth->user('id')), 'fields' => array('Product.id')));
        $conditions = array('Cart.product_id' => $seller_products, 'Cart.order_id >' => 0, 'Cart.payment_status' => 1);
        $orders = array("Cart.add_date" => "DESC");
        $total = $this->Cart->find("count", array("conditions" => $conditions));
        $sum = $this->Cart->find("first", array("conditions" => $conditions, 'fields' => array('sum((Cart.product_cost*Cart.quantity)+Cart.sales_tax+Cart.shipping_cost) AS total')));
        $this->Cart->Behaviors->attach('Containable');
        $this->Cart->contain('Order.id', 'Order.transaction_id', 'Shipping.shipping_method', 'Product.id', 'Product.user_id', 'Product.category_id', 'Product.products_title', 'Product.products_thumbnailImage', 'Product.User.first_name', 'Product.User.last_name', 'User.id', 'User.first_name', 'User.last_name');
        $this->paginate = array('limit' => 10, "conditions" => $conditions, "order" => $orders);
        $this->set('solds', $this->paginate('Cart'));
        $this->set(compact('total', 'sum'));
        $this->layout = "innerhome";
    }

    function search_sold() {
        $this->layout = FALSE;
        $this->Product->recursive = -1;
        $seller_products = $this->Product->find("list", array('conditions' => array("Product.user_id" => $this->Auth->user('id'), $key => $value), 'fields' => array('Product.id')));
        $this->Cart->Behaviors->attach('Containable');
        if ($this->data) {
            if ($this->data["search_by"] == "") {
                $this->autoRender = FALSE;
                echo '<br /><br /><h2>Please Choose an option from dropdown</h2>';
                return;
            }
            if ($this->data["search_by"] == "buyer_id") {
                $conditions = array("Cart.user_id" => $this->data["keywords"]);
            } else {
                if ($this->data["search_by"] == "item_title") {
                    $conditions = array("Product.products_title LIKE" => "%" . $this->data["keywords"] . "%");
                }
                if ($this->data["search_by"] == "item_number") {
                    $conditions = array("Product.id" => $this->data["keywords"]);
                }
            }
            $total = $this->Cart->find("count", array("conditions" => $conditions));
            $sum = $this->Cart->find("first", array("conditions" => $conditions, 'fields' => array('sum(Cart.product_cost*Cart.quantity) AS total')));
            $this->Cart->Behaviors->attach('Containable');
            $this->Cart->contain('Order.id', 'Order.transaction_id', 'Shipping.shipping_method', 'Product.id', 'Product.user_id', 'Product.category_id', 'Product.products_title', 'Product.products_thumbnailImage', 'Product.User.first_name', 'Product.User.last_name', 'User.id', 'User.first_name', 'User.last_name');
            $this->paginate = array('limit' => 10, "conditions" => $conditions, "order" => $orders);
            $this->set('solds', $this->paginate('Cart'));
            $this->set(compact('total', 'sum'));
        }
    }

    function add_tracking($id=null) {
        $this->layout = false;
        $this->loadModel('Order');
        if (!empty($this->data)) {
            $this->Order->save($this->data);
            $this->Session->setFlash(__('Tracking ID has been updated successfully.', true));
            $this->render('success');
        }
        $this->Order->recursive = -1;
        $transaction_id = $this->Order->findById($id, array('fields' => "Order.id,Order.transaction_id"));
        $this->set('transaction_id', $transaction_id);
    }

    function contact_buyer($id=null) {
        $this->layout = false;
        $this->loadModel('Order');
        $this->Order->bindModel(
                array('belongsTo' => array(
                        'Seller' => array(
                            'className' => 'User',
                            'foreignKey' => 'seller_id'
                        ),
                        'Product' => array(
                            'className' => 'Product',
                            'foreignKey' => 'product_id'
                        ),
                        'User' => array(
                            'className' => 'User',
                            'foreignKey' => 'user_id'
                        )
                    )
                )
        );
        if (!empty($this->data)) {
            $this->loadModel('Message');
            $this->loadModel('MessageTrack');
            $this->Message->create();
            if ($this->Message->save($this->data)) {
                $mid = $this->Message->getLastInsertID();
                /////////for sent item//////									
                $this->data['MessageTrack']['message_id'] = $mid;
                $this->data['MessageTrack']['msg_type'] = 0;
                $this->data['MessageTrack']['read'] = 0;
                $this->data['MessageTrack']['star'] = 0;
                $this->MessageTrack->save($this->data);
                ///////////for inbox///////					
                $this->data['MessageTrack']['id'] = null;
                $this->data['MessageTrack']['message_id'] = $mid;
                $this->data['MessageTrack']['msg_type'] = 1;
                $this->data['MessageTrack']['read'] = 0;
                $this->data['MessageTrack']['star'] = 0;
                $this->MessageTrack->save($this->data);
                $this->Session->setFlash(__('The message has been sent successfully.', true));
                $this->render("success");
            } else {
                $this->Session->setFlash(__('The message could not be sent. Please, try again.', true));
            }
        }
        $this->Order->recursive = -1;
        $this->Order->Behaviors->attach('Containable');
        $qData = $this->Order->find("all", array(
            'conditions' => array('Order.product_id' => $id),
            'contain' => array('User.id', 'User.first_name', 'User.last_name', 'Product.id', 'Product.products_title', 'Product.user_id', 'Product.products_price', 'Product.products_expiredDate', 'Product.products_thumbnailImage')
                ));

        $this->set('qData', $qData);
    }

    function create_dispute($pid=null, $cid=null) {
        $this->layout = FALSE;
        $this->loadModel('Dispute');
        if (!empty($this->data)) {

            $this->data['Dispute']['disputer_id'] = $this->Auth->user('id');
            $this->data['Dispute']['expire_date'] = date('Y-m-d', strtotime('+45 days'));
            $this->data['Dispute']['open_date'] = date('Y-m-d');
            $this->data['Dispute']['status'] = 'Pending Mediation';

            $chkext = $this->Dispute->find('count', array('conditions' => array('Dispute.seller_id' => $this->data['Dispute']['seller_id'], 'Dispute.disputer_id' => $this->Auth->user('id'), 'Dispute.product_id' => $this->data['Dispute']['product_id'])));
            if ($chkext == 0) {
                if ($data = $this->Uploader->uploadAll()) {
                    if (!empty($data['image1']['name'])) {
                        $this->data['Dispute']['image1'] = $data['image1']['name'];
                    }
                    if (!empty($data['image2']['name'])) {
                        $this->data['Dispute']['image2'] = $data['image2']['name'];
                    }
                    $this->Dispute->save($this->data['Dispute']);
                } else {
                    $this->data['Dispute']['image1'] = '';
                    $this->data['Dispute']['image2'] = '';
                    $this->Dispute->save($this->data['Dispute']);
                }

                $this->render('dispute_success');
            } else {
                $this->render('dispute_already');
            }
        }
        //$this->Product->recursive = 1;
        $this->Cart->Behaviors->attach('Containable');
        $this->Cart->contain('User.username');
        $conditions = array("Product.id" => $pid, "Cart.id" => $cid);
        $contains = array('Product.id', 'Product.products_title', 'Product.user_id');
        $productinfo = $this->Cart->find("first", array('conditions' => $conditions, 'contain' => $contains));
        $this->set('productinfo', $productinfo);
    }

    function seller_dispute() {
        $this->layout = "innerhome";
        $this->loadModel('Dispute');
        $this->Dispute->Behaviors->attach('Containable');
        $this->Dispute->contain('Disputer.username');
        $disputelist = $this->Dispute->find('all', array('conditions' => array('Dispute.seller_id' => $this->Auth->user('id'))));
        $this->set('disputelist', $disputelist);
    }

    function viewdispute($id=null) {
        $this->layout = null;
        $this->loadModel('Dispute');
        $this->Dispute->Behaviors->attach('Containable');
        $this->Dispute->contain('Disputer.username', 'Product');
        $this->set('disputelist', $this->Dispute->find('first', array('conditions' => array('Dispute.id' => $id))));
    }

    function buyer_dispute() {
        $this->layout = "innerhome";
        $this->loadModel('Dispute');
        $this->Dispute->Behaviors->attach('Containable');
        $this->Dispute->contain('Seller.username');
        $disputelist = $this->Dispute->find('all', array('conditions' => array('Dispute.disputer_id' => $this->Auth->user('id'))));
        $this->set('disputelist', $disputelist);
    }

    function backstage_sadmin_dispute() {
        $this->layout = "admin";
        $this->loadModel('Dispute');
        $this->Dispute->Behaviors->attach('Containable');
        $this->Dispute->contain('Seller.username');
        $disputelist = $this->Dispute->find('all', array('conditions' => array('Dispute.disputer_id' => $this->Auth->user('id'))));
        $this->set('disputelist', $disputelist);
    }

    function close_dispute($id=null) {
        $this->layout = false;
        $this->autoRender = false;
        $this->loadModel('Dispute');
        $this->Dispute->id = $id;
        $this->Dispute->saveField('status', 'Resolved');
    }

    function mediation_dispute($id=null) {
        $this->layout = false;
        $this->autoRender = false;
        $this->loadModel('Dispute');
        $this->Dispute->id = $id;
        $this->Dispute->saveField('involved_sadmin', '1');
        $this->Dispute->id = $id;
        $this->Dispute->saveField('status', 'Pending Mediation');
    }

    function addnote_dispute($id=null) {
        $this->layout = false;
        $this->loadModel('Disputenote');
        if (!empty($this->data)) {
            $this->data['Disputenote']['user_id'] = $this->Auth->user('id');
            $this->Disputenote->save($this->data);
            $this->Session->setFlash(__('The Note has been added Successfully.', true));
            $this->Render('success');
        } else {
            $this->set('id', $id);
        }
    }

    function getdisputenote($id=null) {
        $this->layout = false;
        $this->autoRender = false;
        $this->loadModel('Disputenote');
        return $this->Disputenote->find('all', array('conditions' => array('Disputenote.case_id' => $id, 'Disputenote.user_id' => $this->Auth->user('id'))));
    }

    function monthly_sales_report() {
        $this->layout = 'homereport';
        $chk = 'www';
        $this->loadModel('Order');

        if (isset($_POST['start'])) {
            $previousweek = $this->Cart->find('first', array('fields' => array('Cart.id', 'sum(Cart.quantity * Cart.product_cost) as totalsale', 'Cart.add_date', 'DATE_FORMAT(add_date,"%u") as week'), 'conditions' => array('Cart.payment_status' => 1, 'Cart.add_date <' => date('Y-m-d', strtotime($_POST['start'])), 'Cart.seller_id' => $this->Auth->User('id')), 'recursive' => '-1', 'order' => 'Cart.add_date desc', 'group' => 'week'));
            if (empty($previousweek)) {
                $previousweek = 0;
            } else {
                $previousweek = $previousweek[0]['totalsale'];
            }
            $this->set('previousweek', $previousweek);
            $totalproduct = $this->Cart->find('all', array('fields' => array('Cart.id', 'Cart.add_date', 'sum(Cart.quantity) as tquantity', 'DATE_FORMAT(add_date,"%u") as week'), 'conditions' => array('Cart.payment_status' => 1, 'Cart.add_date BETWEEN ? AND ?' => array(date('Y-m-d', strtotime($_POST['start'])), date('Y-m-d', strtotime($_POST['end']))), 'Cart.seller_id' => $this->Auth->User('id')), 'recursive' => '-1', 'order' => 'week asc', 'group' => 'week'));
            $totalbuyers = $this->Cart->find('all', array('fields' => array('Cart.id', 'count(DISTINCT Cart.user_id) as totalbuyer', 'DATE_FORMAT(add_date,"%u") as week'), 'conditions' => array('Cart.payment_status' => 1, 'Cart.add_date BETWEEN ? AND ?' => array(date('Y-m-d', strtotime($_POST['start'])), date('Y-m-d', strtotime($_POST['end']))), 'Cart.seller_id' => $this->Auth->User('id')), 'recursive' => '-1', 'order' => 'week asc', 'group' => 'week'));
            $this->set('totalbuyers', $totalbuyers);
            $totalsales = $this->Cart->find('all', array('fields' => array('Cart.id', 'sum(Cart.quantity * Cart.product_cost) as totalsale', 'DATE_FORMAT(add_date,"%u") as week'), 'conditions' => array('Cart.payment_status' => 1, 'Cart.add_date BETWEEN ? AND ?' => array(date('Y-m-d', strtotime($_POST['start'])), date('Y-m-d', strtotime($_POST['end']))), 'Cart.seller_id' => $this->Auth->User('id')), 'recursive' => '-1', 'order' => 'week asc', 'group' => 'week'));
            $this->set('totalsales', $totalsales);
            $this->set('startdate', $_POST['start']);
            $this->set('enddate', $_POST['end']);
        } else {
            $totalproduct = null;
            $chk = 'authentic';
        }
        $this->set('totalproduct', $totalproduct);
        $this->set('chk', $chk);
    }

    function admin_monthly_sales_report() {
        $this->layout = 'homereport';
        $chk = 'www';
        if (isset($_POST['start'])) {
            $this->loadModel('Order');
            $previousweek = $this->Cart->find('first', array('fields' => array('Cart.id', 'sum(Cart.quantity * Cart.product_cost) as totalsale', 'Cart.add_date', 'DATE_FORMAT(add_date,"%u") as week'), 'conditions' => array('Cart.payment_status' => 1, 'Cart.add_date <' => date('Y-m-d', strtotime($_POST['start']))), 'recursive' => '-1', 'order' => 'Cart.add_date desc', 'group' => 'week'));
            if (empty($previousweek)) {
                $previousweek = 0;
            } else {
                $previousweek = $previousweek[0]['totalsale'];
            }
            $this->set('previousweek', $previousweek);
            $totalproduct = $this->Cart->find('all', array('fields' => array('Cart.id', 'Cart.add_date', 'sum(Cart.quantity) as tquantity', 'DATE_FORMAT(add_date,"%u") as week'), 'conditions' => array('Cart.payment_status' => 1, 'Cart.add_date BETWEEN ? AND ?' => array(date('Y-m-d', strtotime($_POST['start'])), date('Y-m-d', strtotime($_POST['end'])))), 'recursive' => '-1', 'order' => 'week asc', 'group' => 'week'));
            $totalbuyers = $this->Cart->find('all', array('fields' => array('Cart.id', 'count(DISTINCT Cart.user_id) as totalbuyer', 'DATE_FORMAT(add_date,"%u") as week'), 'conditions' => array('Cart.payment_status' => 1, 'Cart.add_date BETWEEN ? AND ?' => array(date('Y-m-d', strtotime($_POST['start'])), date('Y-m-d', strtotime($_POST['end'])))), 'recursive' => '-1', 'order' => 'week asc', 'group' => 'week'));
            $this->set('totalbuyers', $totalbuyers);
            $totalsales = $this->Cart->find('all', array('fields' => array('Cart.id', 'sum(Cart.quantity * Cart.product_cost) as totalsale', 'DATE_FORMAT(add_date,"%u") as week'), 'conditions' => array('Cart.payment_status' => 1, 'Cart.add_date BETWEEN ? AND ?' => array(date('Y-m-d', strtotime($_POST['start'])), date('Y-m-d', strtotime($_POST['end'])))), 'recursive' => '-1', 'order' => 'week asc', 'group' => 'week'));
            $this->set('totalsales', $totalsales);
            $this->set('startdate', $_POST['start']);
            $this->set('enddate', $_POST['end']);
        } else {
            $totalproduct = null;
            $chk = 'authentic';
        }
        $this->set('totalproduct', $totalproduct);
        $this->set('chk', $chk);
    }

    function orderdetails($startdate=null, $enddate=null, $weekno=null) {
        $this->layout = false;
        $this->autoRender = false;
        $this->loadModel('Order');
        //$this->Order->recursive = 2;
        return $this->Cart->find('all', array('fields' =>
                    array('Cart.id', 'Cart.quantity', 'Cart.product_cost', 'Cart.user_id', 'Shipping.shipping_method', 'Product.products_thumbnailImage'
                        , 'Product.products_title', 'Product.id', 'User.username', 'Cart.add_date', 'Order.transaction_id'),
                    'conditions' => array('Cart.payment_status' => 1, 'Cart.add_date BETWEEN ? AND ?' => array(date('Y-m-d', strtotime($startdate)),
                            date('Y-m-d', strtotime($enddate))), 'DATE_FORMAT(Cart.add_date,"%u")' => $weekno), 'order' => 'Cart.user_id asc'));
    }

    function delete_reportitem($id=null) {
        $this->layout = FALSE;
        $this->loadModel('Reporteditem');
        //$this->Reportnote->id=$id;
        $this->Reporteditem->delete($id);
        $this->autoRender = false;
    }

    function generatereport($startdate=null, $enddate=null) {
        $this->layout = null;
        $this->autoLayout = false;
        $this->loadModel('Order');
        $this->Order->Behaviors->attach('Containable');
        $reports = $this->Order->find('all', array('fields' => array('Order.id', 'Order.quantity', 'Order.product_cost', 'Order.user_id', 'Order.add_date'),
            'contain' => array(
                'Product.id', 'Product.products_title', 'User.username', 'Seller.username'
            ),
            'conditions' => array('Order.add_date BETWEEN ? AND ?' =>
                array(date('Y-m-d', $startdate), date('Y-m-d', $enddate))),
            'order' => 'Order.id asc'));

        $this->set('reports', $reports);
    }

    function brand_menu($type=null) {
        $this->layout = null;
        $this->autoRender = false;
        //$type='global_brands';

        $this->Product->Behaviors->attach('Containable');
        if ($type == 'global_brands') {
            return $this->Product->find('all', array('fields' =>
                        array('Product.id', 'count(Product.' . $type . ') as totalproduct'),
                        'conditions' => array('Product.products_expiredDate >=' => date('Y-m-d H:i:s'), 'OR' => array(array('Product.products_status !=' => 'Disapproved'), array('Product.products_status !=' => 'Pending'))),
                        'contain' => array('Brand.id', 'Brand.brand_description'),
                        'order' => 'totalproduct desc', 'group' => 'Product.' . $type, 'limit' => 5));
        }
        if ($type == 'global_conditions') {
            return $this->Product->find('all', array('fields' =>
                        array('Product.id', 'count(Product.' . $type . ') as totalproduct'),
                        'conditions' => array('Product.products_expiredDate >=' => date('Y-m-d H:i:s'), 'OR' => array(array('Product.products_status !=' => 'Disapproved'), array('Product.products_status !=' => 'Pending'))),
                        'contain' => array('ProductCondition.id', 'ProductCondition.brand_description'),
                        'order' => 'totalproduct desc', 'group' => 'Product.' . $type));
        }

        if ($type == 'global_styles') {
            return $this->Product->find('all', array('fields' =>
                        array('Product.id', 'count(Product.' . $type . ') as totalproduct'),
                        'conditions' => array('Product.products_expiredDate >=' => date('Y-m-d H:i:s'), 'OR' => array(array('Product.products_status !=' => 'Disapproved'), array('Product.products_status !=' => 'Pending'))),
                        'contain' => array('ProductStyle.id', 'ProductStyle.brand_description'),
                        'order' => 'totalproduct desc', 'group' => 'Product.' . $type));
        }
    }

    function gallery_popup($id=null) {
        $this->layout = null;
        $this->Product->recursive = -1;
        $pid = $id;
        $thumb = $this->Product->findById($id);
        $this->ProductImage->recursive = -1;
        $images = $this->ProductImage->find("all", array("conditions" => array("ProductImage.product_id" => $id), "order" => array("ProductImage.id" => "desc")));
        $this->set(compact('thumb', 'images', 'pid'));
    }

    function size_menu() {
        $this->layout = null;
        $this->autoRender = false;
        $this->loadModel('Sizevalue');

        $allsizes = $this->Sizevalue->find('all', array('order' => 'Sizevalue.size_value  asc', 'group' => 'Sizevalue.size_value', 'recursive' => '-1'));
        $i = 0;
        foreach ($allsizes as $allsizevalue) {
            $sizeproductcount = $this->ProductSize->find('count', array('conditions' => array('ProductSize.sizevalue_id' => $allsizevalue['Sizevalue']['id']), 'recursive' => '-1'));
            if ($sizeproductcount > 0) {
                $sizemenu[$i] = $allsizevalue['Sizevalue']['id'] . '@' . $allsizevalue['Sizevalue']['size_value'];
                $i++;
            }
        }
        return $sizemenu;
    }

    function color_menu() {
        $this->layout = null;
        $this->autoRender = false;
        $this->loadModel('Field');
        $color = $this->Field->find('all', array('fields' => array('Field.id'), 'conditions' => array('Field.field_name' => 'Color'), 'order' => 'Field.id  asc', 'recursive' => '-1'));
        $results = Set::extract('/Field/id', $color);
        return $this->ProductAdditionalFieldValue->find('all', array('fields' => array('ProductAdditionalFieldValue.values', 'count(ProductAdditionalFieldValue.values) as totalproduct'), 'conditions' => array('ProductAdditionalFieldValue.field_id' => $results), 'order' => 'ProductAdditionalFieldValue.values  asc', 'group' => 'ProductAdditionalFieldValue.values', 'recursive' => '-1'));
    }

    function autobrand($id=null, $type=null) {
        Configure::write('debug', 0);
        $this->layout = 'ajax';
        $this->recursive = 0;

        $conditions = array('Categorybrand.category_id' => $id, 'Categorybrand.brand_type' => $type, 'Brand.brand_description LIKE' => $this->params['url']['q'] . '%');
        $order = array('Brand.brand_description' => 'asc');
        $brands = $this->Categorybrand->find('all', array('conditions' => $conditions, 'order' => $order));
        $this->set('brands', $brands);
    }

}

?>